ReactJS从父级到子级传递状态

时间:2019-02-06 07:27:29

标签: javascript reactjs

我有以下内容,并且想知道是否还有一种更优雅的方法将this.state.currentSection状态传递给<HeaderButton />

...
render() {
        return <div>
            <div className="section" style={this.state.currentSection === 'SPECIAL' ? {} : {'opacity': '0.4'}}>
                <HeaderButton active={this.state.currentSection === 'SPECIAL'} text="Special" count={23} backgoundColor={'#c04c36'} onClick={this.setActiveSpecial}/>
            </div>
...

5 个答案:

答案 0 :(得分:1)

您可以像这样在render方法中破坏this.state

render() {
  const { currentSection } = this.state;
  const isActive = (currentSection === 'SPECIAL');
  return (
   <div className="section" style={isActive ? {} : {'opacity': '0.4'}}>
     <HeaderButton active={isActive} text="Special" count={23} backgoundColor={'#c04c36'} onClick={this.setActiveSpecial}/>
   </div>
  );
}

答案 1 :(得分:0)

您可以为此使用单个变量,而不必两次编写this.state.currentSectionBoolean(null) === false

render() {
        let value = (this.state.currentSection === "SPECIAL") ? null : {opacity:'0.4'}; 
        return (<div>
            <div className="section" style={value}>
                <HeaderButton active={Boolean(value)} text="Special" count={23} backgoundColor={'#c04c36'} onClick={this.setActiveSpecial}/>
            </div>)
}

答案 2 :(得分:0)

您可以使用JavaScript spread notation

render() {
    const headerButtonState = {
          active:this.state.currentSection === 'SPECIAL',
          text:"Special",
          count:23, 
          backgoundColor:'#c04c36'
    }
    return <div>
            <div className="section" style={this.state.currentSection === 'SPECIAL' ? {} : {'opacity': '0.4'}}>
                <HeaderButton {...headerButtonState} onClick={this.setActiveSpecial}/>
            </div>
     }

答案 3 :(得分:0)

如果您只想处理一种情况,而不是三元使用&&。

即,而不是:

isActive ? <Component/> : null;

使用:

isActive && <Component/>

答案 4 :(得分:0)

我将根据该部分的--special类修饰符来修改CSS中所有与样式相关的内容。

import classnames from 'classnames';

...

render() {
  const { currentSection } = this.state;
  const isSectionSpecial = currentSection === 'SPECIAL';

  return (
    <div>
      <div className={classnames('section', {
        'section--special': isSectionSpecial
      })}>
        <HeaderButton active={isSectionSpecial} />
      </div>
    </div>
  )
}

CSS

.section {
  ...
}

.section--special {
  opacity: 0.4;
}

.header-button {
  ...
}

.section--special .header-button {
  background-color: #c04c36;
}
相关问题