【问题标题】:React.js child component not updating styling derived from props, why? (styled-components)React.js 子组件不更新从道具派生的样式,为什么? (样式化组件)
【发布时间】:2018-10-15 23:17:54
【问题描述】:

我是 react.js 的新手,我正在尝试根据从父组件传递的道具了解条件样式。

我正在尝试制作一个样式差异的按钮,具体取决于“禁用”道具是真还是假。如果按钮被禁用 (true),它应该显示为灰色,否则为蓝色。

这是我目前的代码,虽然它不工作,我不知道为什么。

父组件

import React from 'react';

import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { linkTo } from '@storybook/addon-links';

import { Welcome } from '@storybook/react/demo';
// Buttons
import Primary from '../components/ButtonPrimary'

storiesOf('Welcome', module).add('to Storybook', () => <Welcome showApp={linkTo('Button')} />);

storiesOf('Buttons')
    .add('Primary', () => <Primary label="Default" disabled="false"></Primary>)

子组件

import React from "react";
import styled from 'styled-components';

const Button = styled.button`
    background-color: ${props => props.disabled ? '#EDEDED' : '#0076C0'};
    border: ${props => props.disabled ? '1px solid #DADADA' : 'none'};    
    color: ${props => props.disabled ? '#818181' : '#FFFFFF'};
    cursor: ${props => props.disabled ? 'unset' : 'pointer'};
    border-radius: 2px;
    font-family: Roboto-Regular;
    font-size: 16px;
    padding: 6px 32px;
    font-family: roboto, helvetica, sans-serif;
    font-size: 18px;

    &:focus {
        outline: none;
    }

    &:hover {
        box-shadow: ${props => props.disabled ? 'unset' : '0px 1px 2px 1px #b3b3b3'};
    }

    &:active {
        box-shadow: ${props => props.disabled ? 'unset' : 'inset 0 0 10px #2f2f2f80'};
    }
`;

export default class ButtonPrimary extends React.Component {
    render() {
        return (
            <div>
                <Button disabled={this.props.disabled}>{this.props.label}</Button>
            </div>
        )
    }
}

有人知道为什么吗?

【问题讨论】:

    标签: javascript node.js reactjs styled-components react-props


    【解决方案1】:

    在您的父组件中,您需要将disabled 更改为布尔值而不是字符串。

    storiesOf('Buttons')
        .add('Primary', () => <Primary label="Default" disabled={false} ></Primary>)
    

    或者如果您需要将其用作字符串,则需要指定条件

    ${props => props.disabled === 'true' ? '#EDEDED' : '#0076C0'};
    

    【讨论】:

    • 将此作为一个很好的答案并使用disabled 显示为true(没有={})以及
    猜你喜欢
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 2017-08-11
    • 2019-02-12
    • 2015-06-25
    • 1970-01-01
    • 2018-05-18
    相关资源
    最近更新 更多