其他分享
首页 > 其他分享> > React 基础 - 07 (双向绑定、条件渲染)

React 基础 - 07 (双向绑定、条件渲染)

作者:互联网

1、双向绑定

        双向数据流 数据<=>页面 收集表单用户输入信息

        input中需要绑定onChange方法,带有参数event,修改对应的state数据

export default class App extends Component {
  state = { name: "皮卡丘" };
  render() {
    const { name } = this.state;
    return (
      <div>
        <input type="text" value={name} onChange={this._nameChange} />
        <input
          type="text"
          value={name}
          onChange={e => {
            this.setState({ name: e.target.value });
          }}
        />
        <div>{name}</div>
      </div>
    );
  }
  _nameChange = e => {
    this.setState({ name: e.target.value });
  };
}

2、条件渲染

        JS原生代码写法

export default class App extends Component {
  score = 60;
  _changeScore(num) {
    this.score += num;
    this.setState({});
  }
  render() {
    return (
      <div>
        <h3>0.0</h3>
        <h3>分数:{this.score}</h3>
        <button onClick={this._changeScore.bind(this,10)} disabled={this.score>=100}>分数+10</button>
        <button onClick={this._changeScore.bind(this,-10)} disabled={this.score<=0}>分数-10</button>
        {/* {60分以上及格,否则不及格} */}
        {this.show()}
      </div>
    );
  }
  show(){
    if(this.score>=60) return <div style={{color:'green'}}>及格了</div>
    return <div style={{color:'red'}}>不及格</div>
  }
}

标签:60,return,07,绑定,React,state,score,setState,name
来源: https://blog.csdn.net/Janicecat/article/details/121939215