App.js
import Parent from './Parent'
function App(){
return (
<div>
<Parent></Parent>
</div>
)
}
export default App
parents.js
// react中父子组件传值
// 父向子: 父组件通过自定义属性向子组件传值,子组件通过this.props.属性名接收
// 子向父: 子组件通过调用父组件以props传入的方法来更改父组件的数据
import React, { Component } from 'react';
import Child from './Child'
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
msg: '我是父组件的数据',
list: ['a','b']
}
}
//在父组件定义,但是为了让子组件调用的方法
changeMsg(newMsg){
console.log('我是被子组件调用',newMsg);
this.setState({
msg: newMsg
})
}
render() {
//对state数据解构赋值
let {msg,list} = this.state
return (
<div>
<h1>父组件的内容:{msg}</h1>
<hr></hr>
<h2>子组件的内容</h2>
{/* 父组件通过自定义属性向子组件传值 */}
<Child msg1={msg} num={3} list={list} changeMsg1={this.changeMsg.bind(this)}></Child>
</div>
)
}
}
export default Parent;
Child.js
import React, { Component } from 'react';
import './Child.css'
class Child extends Component {
constructor(props) {
super(props);
this.state = {
nickname: '子组件昵称'
}
}
//在子组件内部直接更改父组件的数据
// 结论: 不要在子组件内部直接改更
// changeParent1 = ()=>{
// // console.log(this.props.msg1)
// // console.log(this.props.list)
// //父组件传入的数据不能通过子组件直接修改
// // this.props.msg1 = 'new'
// }
changeParent2 = ()=>{
let { nickname } = this.state
this.props.changeMsg1(nickname)
}
render() {
return (
<div className="child-box">
<div>显示父组件传来的数据: {this.props.msg1}---{this.props.num}</div>
<div><button onClick={this.changeParent1}>错误做法:在子组件内部直接更改父组件的数据</button></div>
<div>
{/* <button onClick={()=>this.props.changeMsg(this.state.nickname)}>正确做法:通过子组件更改父组件的数据</button>
</div> */}
<button onClick={this.changeParent2}>正确做法:通过子组件更改父组件的数据</button>
</div>
</div>
);
}
}
export default Child;
网友评论