初学react(五):双向数据绑定

React双向数据绑定

input组件双向数据绑定,需要父组件暴露一个数据更新方法传递给子组件,input使用onChange触发,然后获取对应改变的值,重新setstate,用defaultValue 替换value作为默认值

//persion.js
import React from 'react';
const person = ( props ) => {
    return (
        <div>
            <p onClick={props.myclick}>大家好,我系{props.name},我有{props.count}作品</p>
            <p>{props.children}</p>
            <input type="text" onChange={props.changed} defaultValue={props.name}></input>
        </div>
        
    )
}
export default person;


//app.js

import React from 'react';
import './App.css';
import Persion from './Persion/Persion';
class App extends React.Component {
  /**
   * state: 用于改变组件内状态的值(动态)
   * props: 用于组件通信传值
   */
  state = {
   persions: [
     {
       name: '渣渣辉',
       count: '30'
     },
     {
        name: 'aaa',
        count: '20'
      },
      {
        name: 'bbb',
        count: '10'
      },
      {
        name: 'ccc',
        count: '5'
      }
   ],
   otherState: 'anything'
  }
  // 函数直接定义在于render同级别,因为class类下,用this.函数名来访问
  switchNameHandLer = ( newName ) => {
    console.log("hello")
    // es6中this执行为当前类
    //this.state.persions[0].name = '渣渣渣渣辉' //不要直接去更改state Use setState()
    this.setState({
      persions: [
        {
          name: newName,
          count: '3000'
        },
        {
          name: 'aaa',
          count: '20'
        },
        {
          name: 'bbb',
          count: '10'
        },
        {
          name: 'ccc',
          count: '5'
        }
      ]
    })
  }  
  nameChangedHandLer = (event) => {
    console.log(event.target)
    this.setState({
      persions: [
        {
          name: event.target.value,
          count: '3000'
        },
        {
          name: 'aaa',
          count: '20'
        },
        {
          name: 'bbb',
          count: '10'
        },
        {
          name: 'ccc',
          count: '5'
        }
      ]
    })
  }
  render () {
    return (
      <div className="App">
        hello world
        {/* 函数不能加括号,加括号就直接执行了,使用箭头函数可以实现参数的传递 */}
        {/* <button onClick={() => this.switchNameHandLer('古天乐')}>更改状态值</button> */}
        {/* 第二种方式  bind 传递 (建议) */}
        <button onClick={this.switchNameHandLer.bind(this, '古天乐')}>更改状态值</button>
        <Persion 
          name={this.state.persions[0].name}
          count={this.state.persions[0].count}
          changed={this.nameChangedHandLer}
          />
        <Persion 
          name={this.state.persions[1].name}
          myclick={this.switchNameHandLer.bind(this, '渣渣辉2')}
          count={this.state.persions[1].count}/>
        <Persion name={this.state.persions[2].name}
         count={this.state.persions[2].count}/>
        <Persion name={this.state.persions[3].name}
         count={this.state.persions[3].count}>
          <a href='http://www.baidu.com'>非常感谢大家的支持</a>
        </Persion>
      </div>
    );
  }
}
export default  App;

触发,然后获取对应改变的值,重新setstate

猜你喜欢

转载自blog.csdn.net/qq_37942845/article/details/90212525