You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React组件传参疑问:子传父需先声明父方法参数吗?

React子组件向父组件传参的疑问解答

你的组件代码

class ParentComponent extends Component {
    constructor(props) {
      super(props)
    
      this.state = {
         parentName: 'Parent'
      }
      this.greetParent = this.greetParent.bind(this)
    }
        // define a method call 'greetParent'
        greetParent(childName){
            alert(`Hello ${this.state.parentName} from ${childName}`)
        }
    
  render() {
    return (
      <div>
        <ChildComponent greetHandler={this.greetParent}></ChildComponent>
      </div>
    )
  }
}

function ChildComponent(props) {
  return (
    <div>
      <button onClick={() =>props.greetHandler('child')}>Greet Parent</button>
    </div>
  )
}

疑问解答

  1. 子组件向父组件传参时,是否需要先在父组件的greetParent方法中声明参数名?
    是的,必须声明。父组件的greetParent方法要接收子组件传递的值,就得通过参数来承接。如果不声明参数,方法内部就无法获取子组件传过来的'child',也就没法在逻辑里使用这个值。

  2. 是否只需在子组件中设置参数值(如示例中的'child'),该参数就会自动传入父组件的greetParent方法中?
    没错。当你在子组件点击事件里调用props.greetHandler('child')时,'child'会作为参数直接传递给父组件的greetParent方法。只要父组件的方法已经声明了对应参数(比如示例里的childName),就能直接拿到这个值使用。

内容的提问来源于stack exchange,提问作者Cocopapoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 04:02:52