如何检查样式组件内的状态?

时间:2017-11-18 10:14:25

标签: javascript reactjs

不是通过内联样式设置Li组件的样式,而是通过样式组件来实现。如果当前Li是所选语言,我该如何检查状态然后将颜色指定为红色?

const Li = styled.li`
  border: 0;

  //Set color to red if this component is selected
  ${this.state => this.state.selectedLanguage`
    color: 'red';
  `}

`;

class Popular extends Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedLanguage: 'All'
        }

        this.updateLanguage = this.updateLanguage.bind(this);
    }

    updateLanguage(lang) {
        this.setState(function() {
            return {
                selectedLanguage: lang
            };
        });
    }
    render() {
        const languages = ['All', 'Javascript', 'Java', 'Go', 'Rust'];
        return (
            <ul className={`list-group d-flex flex-row justify-content-center ${this.props.className}`}>
                {languages.map(function(lang){
                    return (
                        <Li
                            key={lang}
                            // style={lang === this.state.selectedLanguage ? {color: '#d00d1b'} : null}
                            onClick={this.updateLanguage.bind(null, lang)}
                            className={`list-group-item p-2 ${this.props.className}`}>
                            {lang}
                        </Li>
                    )
                }, this)}
            </ul>
        );
    }
}

export default Popular;

代码基于tyler mcginnis - react fundamentals

1 个答案:

答案 0 :(得分:1)

传递isSelected作为道具,然后调用css助手,如果为真

const selectedLanguageStyle = css`
  color: '#d00d1b'
`

const Li = styled.li`
  border: 0;
  ${(props) => props.isSelected && selectedLanguageStyle}
`;

class Popular extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedLanguage: 'All'
    }

    this.updateLanguage = this.updateLanguage.bind(this);
  }

  updateLanguage(lang) {
    this.setState(function() {
      return {
        selectedLanguage: lang
      };
    });
  }
  render() {
    const languages = ['All', 'Javascript', 'Java', 'Go', 'Rust'];
    return (
      <ul className={`list-group d-flex flex-row justify-content-center ${this.props.className}`}>
        {languages.map(function(lang){
          return (
            <Li
              key={lang}
              isSelected={lang === this.state.selectedLanguage}
              onClick={this.updateLanguage.bind(null, lang)}
              className={`list-group-item p-2 ${this.props.className}`}>
              {lang}
            </Li>
          )
        }, this)}
      </ul>
    );
  }
}

export default Popular;
相关问题