ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
* 在react中,数据是单向流动的(即从dom树中自上向下流动) 1.父子通信 在父组件通过注册属性的形式向子组件传递值,子组件通过this.props接受来之父组件的属性及属性值 ~~~ import React from 'react' import Child from './Child.js' export default class Parent extends React.Component { constructor(props) { super(props) this.state = { value: '' } } handleChange(e) { var value = e.target.value; this.setState({ value: value }) } render() { const { value } = this.state return ( <div> 父亲说:<input value={value} onChange={this.handleChange.bind(this)} /> //使用val属性传参 <Child val={value} /> </div> ) } } ~~~ ~~~ import React from 'react' export default class Child extends React.Component{ render() { const { val } = this.props; return ( <div> <p>父亲对儿子说:{val}</p> </div> ) } } ~~~ 2.子父通信 子组件通过调用父组件传递的方法向父组件传值 ~~~ import React from 'react' import Child from './Child.js' export default class Swip extends React.Component { constructor(props) { super(props) this.state = { value: '', childSaid: '' } } handleChange(e) { var value = e.target.value; this.setState({ value: value }) } childSay(val) { this.setState({ childSaid: val }) } render() { const { value, childSaid } = this.state return ( <div> 父亲说:<input value={value} onChange={this.handleChange.bind(this)} /> <Child say={this.childSay.bind(this)} val={value} /> <p>儿子对父亲说:{childSaid}</p> </div> ) } } ~~~ ~~~ import React from 'react' export default class Child extends React.Component { constructor(props) { super(props) this.state = { value: '' } } handleChange(e) { const { say } = this.props; var value = e.target.value; this.setState({ value: value }); // 调用父组件的方法 say(value); } render() { const { val } = this.props; const { value } = this.state; return ( <div> <p>父亲对儿子说:{val}</p> 儿子说:<input value={value} onChange={this.handleChange.bind(this)} /> </div> ) } } ~~~