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)=>{/**子組件觸發(fā)的方法 獲取子組件傳遞的值 */
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;
顯示
image.png