参考链接:https://www.jianshu.com/p/70301fa8619a
父组件:
import React from 'react'
import Home from '../home/Home'
class Good extends React.Component {
constructor(props) {
super(props);
//存放组件所需要的一些状态
this.state = {
inputValue:'Goods父亲传给儿子的值是“111”'
// arr: [10, 20, 30, 40]
}
}
render() {
return (
<div>
<span>我是Goods父亲</span>
<ul>
{/* {
this.state.arr.map((item, index) => (
<li key={index}>{item}</li>
))
} */}
</ul>
<Home
childData={this.state.inputValue}
childClick={this.onClick}
/>
{/* child 是子组件的名称,childData是自己起的名字,inputValue 是父组件中state中定义 */}
</div>
)
}
onClick = ()=>{
console.log('父组件事件')
}
}
export default Good
子组件:
import React from 'react'
class Comment extends React.Component {
constructor(props){
super(props)
}
render() {
console.log(this.props.childData)
return (
<div className="shopping-list">
<span>我是Home儿子</span><br/>
<div>{this.props.childData}</div>
{/* 方法一 */}
<button onClick={this.props.childClick}>点击</button>
{/* 方法二 */}
<button onClick={this.handleClick}>点击</button>
</div>
);
}
handleClick = ()=>{
let {childClick}=this.props
childClick() //绑定在父亲里
}
}
export default Comment