1.0 父组件获取子组件中的值
- parent.js
// import logo from './logo.svg';
import React, {Component} from 'react'
import Children from './children'
export default class Parent extends Component {
constructor(props) {
super(props)
this.state = {
name: '我是父组件',
msg: '父组件传值给子组件',
childrenMsg:'',
newName:'我是父组件中的newName',
newMsg :'父组件传值给子组件中newMsg'
}
this.child = React.createRef(); //父组件获取子组件更新的值
}
getChildrenMsg=()=>{/**父组件获取子组件中的值 */
this.setState({childrenMsg:this.child.current.state.msg })
}
getChildrenMsg2 = (result,msg)=>{/**子组件触发的方法 获取子组件传递的值 */
console.log(result)
this.setState({
childrenMsg:msg
})
}
render() {
return (
<div>
<h2>{ this.state.name }</h2>
<button onClick={ this.getChildrenMsg }>获取更新子组件的msg值</button>
<h3 style={{color:'green'}}>我要引入子组件了</h3>
<h3>子组件传来的值为:{ this.state.childrenMsg }</h3>
<hr />
<Children ref ={this.child} parent={this} newName ={this.state.newName} newMsg = {this.state.newMsg}/>
</div>
)
}
}
- children.js
import React, {Component} from 'react'
export default class Children extends Component {
constructor(props) {
super(props)
this.state = {
name: '我是子组件',
msg: '子组件传值给父组件'
}
}
toParent=()=>{
this.props.parent.getChildrenMsg2(this,this.state.msg);//子组件定义的方法抛出的方法名 用于父组件通过相同的事件名获取自组件传递的值
}
render() {/**this.props获取父组件中所有的值*/
return (
<div>
<h2>{ this.state.name }</h2>
<h3>我是子组件中msg的值{this.state.msg}</h3>
<button onClick = {this.toParent}>子组件传值给父组件</button>
<h4>{this.props.newName}</h4>
<h5>我是子组件中拿到父组件传递过来的newMsg:{this.props.newMsg}</h5>
</div>
)
}
}
- app.js
import React from 'react';
import Parent from './parent'
function App() {
return (
<div>
<Parent/>
</div>
);
}
export default App;
显示