Material UI TextField React Component条件样式不会触发textField渲染

时间:2018-03-29 13:27:59

标签: reactjs material-ui

反应组件:

class Info extends Component {
    constructor() {
       this.state = {
        editAccount: false
       }
       this.changeTrue = this.changeTrue.bind(this);
       this.changeFalse = this.changeFalse.bind(this);
    }
    changeTrue() {
      this.setState({ediAccount: true}
    }
    changeFalse() {
      this.setState({ediAccount: false}
    }
    render() {
        const specific_style = this.state.editAccount ? { background: 'red'} : { background : 'yellow' }
        return (
         <div>
            <TextField
                id='first_name'
                inputStyle={ specific_style}
                value={this.state.first_name}
              />
           <button onClick={this.changeTrue}>Click True</button>
           <button onClick={this.changeFalse}>Click False</button>
         </div>
        )
    }
}

让此组件和editAccount的状态发生变化不会重新呈现应用样式更改吗?不会重新渲染TextField吗?谁知道为什么?

4 个答案:

答案 0 :(得分:1)

  

State Updates May Be Asynchronous

     

React可以批量多个setState()   调用单个更新以获得性能。

     

因为this.propsthis.state可以异步更新,所以   不应该依赖它们的值来计算下一个状态。

根据当前状态更新状态时,请始终在setState()的调用中使用回调。回调获取先前的状态并返回下一个状态。这是因为react可以批量多次调用setState(),因此不使用回调将覆盖以前的调用:

this.setState(prevState => ({editAccount: !prevState.editAccount)});

同样在包含样式的对象中,您使用了变量(未定义)而不是字符串:

const specific_style = this.state.editAccount ? { background: red /* red is not defined*/} : { background : yellow /* same here */ };

应该是:

const specific_style = this.state.editAccount ? { background: 'red' } : { background : 'yellow' };

对象不能像css类一样编写。

完全正常工作的代码必须看起来像这样:

class Info extends Component {
  constructor(props) {
    super(props);

    this.state = {
      editAccount: false
    };

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

  changeStyle() {
    this.setState(state => ({editAccount: !state.editAccount}));
  }

  render() {
    const specific_style = this.state.editAccount ? { background: 'red' } : { background: 'yellow' };
    return (
      <div>
        <TextField
          id="first_name"
          inputStyle={specific_style}
        />
        <button onClick={this.changeStyle}>Toggle red/yellow</button>
      </div>
    );
  }
}

请参阅此working codesandbox example

答案 1 :(得分:0)

看来你忘了把'&lt;'和'/&gt;'在渲染函数的返回范围内。我们两个人做了编辑来解决这个问题,但也许这就是问题

答案 2 :(得分:0)

您可能需要使用像componentWillReceiveProps这样的生命周期方法来强制重新渲染。另外 - 格式化代码

答案 3 :(得分:0)

editAccount在哪里/如何定义?它应来自stateprops以触发重新渲染。

如果render()方法不受props / state更改的影响,则不会触发。

相关问题