在父組件的子組件裏面定製一個屬性,聲明一個對應的方法,而後在子組件中經過this.props去調用對應的方法,拿到對應的值,而後把它進行接收。react
(這種方法簡直就是浪費表情,子組件的值確實能傳遞到add裏面,可是視圖層根本不變。)this
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;