在父组件的子组件里面定制一个属性,声明一个对应的方法,然后在子组件中通过this.props去调用对应的方法,拿到对应的值,然后把它进行接收。
(这种方法简直就是浪费表情,子组件的值确实能传递到add里面,但是视图层根本不变。)
class Comment extends Component {
handleClick=()=>{
this.props.add('子组件的值')
}
render() {
return (
<div className='comment'>
{/* <div className="userinfo"> */}
<UserInfo {...this.props.user}></UserInfo>
{/* avatarUrl={this.props.user.avatarUrl} name={this.props.user.name} */}
<div className="comment-content">评论内容:{this.props.user.content}</div>
<div className="comment-date">评论时间:{this.props.user.date}</div>
<button onClick={this.handleClick}>子传父</button>
{/* </div> */}
</div>
);
}
}
class App extends Component {
constructor(props) {
super(props);
//遵循单向数据流
this.user={
avatarUrl:"https:////car2.autoimg.cn/cardfs/series/g26/M05/B0/29/100x100_f40_autohomecar__ChcCP1s9u5qAemANAABON_GMdvI451.png",
name:'MJJ',
content:'这是我的react组件',
date:new Date().toLocaleTimeString(),
val:'hello'
}
}
add(val){
//alert(val)
this.user.val = val;
}
render() {
return (
<div>
<h2>hello,{this.props.name}</h2>
<h1>{this.user.val}</h1>
<Mybtn title='提交'></Mybtn>
<Mybtn title='删除'></Mybtn>
<Mybtn title='修改'></Mybtn>
<Mybtn title='添加'></Mybtn>
<Comment user={this.user} add={this.add}></Comment>
</div>
)
}
}
export default App;
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。