【问题标题】:ReactJS call parent methodReactJS 调用父方法
【发布时间】:2014-10-03 09:29:08
【问题描述】:

我正在迈出 ReactJS 的第一步,并试图理解父母和孩子之间的沟通。 我正在制作表格,所以我有样式字段的组件。而且我还有包含字段并检查它的父组件。示例:

var LoginField = React.createClass({
    render: function() {
        return (
            <MyField icon="user_icon" placeholder="Nickname" />
        );
    },
    check: function () {
        console.log ("aakmslkanslkc");
    }
})

var MyField = React.createClass({
    render: function() {
...
    },
    handleChange: function(event) {
//call parent!
    }
})

有什么办法吗。我的逻辑在 reactjs“世界”中是否很好?感谢您的宝贵时间。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    为此,您将回调作为属性从父级传递给子级。

    例如:

    var Parent = React.createClass({
    
        getInitialState: function() {
            return {
                value: 'foo'
            }
        },
    
        changeHandler: function(value) {
            this.setState({
                value: value
            });
        },
    
        render: function() {
            return (
                <div>
                    <Child value={this.state.value} onChange={this.changeHandler} />
                    <span>{this.state.value}</span>
                </div>
            );
        }
    });
    
    var Child = React.createClass({
        propTypes: {
            value:      React.PropTypes.string,
            onChange:   React.PropTypes.func
        },
        getDefaultProps: function() {
            return {
                value: ''
            };
        },
        changeHandler: function(e) {
            if (typeof this.props.onChange === 'function') {
                this.props.onChange(e.target.value);
            }
        },
        render: function() {
            return (
                <input type="text" value={this.props.value} onChange={this.changeHandler} />
            );
        }
    });
    

    在上面的示例中,Parent 调用具有 valueonChange 属性的 ChildChild 作为回报将 onChange 处理程序绑定到标准 &lt;input /&gt; 元素,并将值传递给 Parent 的回调(如果已定义)。

    因此,ParentchangeHandler 方法被调用,第一个参数是来自Child&lt;input /&gt; 字段的字符串值。结果是Parent 的状态可以使用该值进行更新,从而导致父级的&lt;span /&gt; 元素在您在Child 的输入字段中键入时使用新值进行更新。

    【讨论】:

    • 我认为您需要先绑定父函数,然后再将其传递给子函数:&lt;Child value={this.state.value} onChange={this.changeHandler.bind(this)} /&gt;
    • @o01 不,因为我使用的是React.createClass,它会自动绑定所有组件方法。如果我使用的是 React es6 类,那么你需要绑定它(除非你在构造函数中自动绑定,这是现在很多人为了解决这个问题所做的)
    • @MikeDriver 我明白了。不知道这仅限于使用 ECMAScript 6 类(我是)的情况。也不知道 React 团队 recommends 在构造函数中自动绑定。
    • 我不知道他们是否推荐它,但这似乎是我看到的很常见的事情。对我来说,这比将绑定放在渲染线程中更有意义,因为 .bind 返回一个新函数,所以基本上每次运行渲染时都会创建一个新函数。这可能很好,但是如果您在构造函数中绑定,那么您只需在实例化时为每个组件方法执行一次,而不是每次渲染。这是挑剔的......但我想技术上更好!
    • @DavidLy-Gagnon 在示例中它可能未定义,因为我没有在 propType 上附加 isRequired。但是,是的,您可以这样做,或者只是检查它是否已定义。
    【解决方案2】:

    2019 年 React 16+ 和 ES6 更新

    由于React.createClass 已从 React 版本 16 中弃用,因此发布此内容,新的 Javascript ES6 将为您带来更多好处。

    父母

    import React, {Component} from 'react';
    import Child from './Child';
      
    export default class Parent extends Component {
    
      es6Function = (value) => {
        console.log(value)
      }
    
      simplifiedFunction (value) {
        console.log(value)
      }
    
      render () {
      return (
        <div>
        <Child
              es6Function = {this.es6Function}
              simplifiedFunction = {this.simplifiedFunction} 
            />
        </div>
        )
      }
    
    }
    

    孩子

    import React, {Component} from 'react';
    
    export default class Child extends Component {
    
      render () {
      return (
        <div>
        <h1 onClick= { () =>
                this.props.simplifiedFunction(<SomethingThatYouWantToPassIn>)
              }
            > Something</h1>
        </div>
        )
      }
    }
    

    将无状态子简化为 ES6 常量

    import React from 'react';
    
    const Child = (props) => {
      return (
        <div>
        <h1 onClick= { () =>
            props.es6Function(<SomethingThatYouWantToPassIn>)
          }
          > Something</h1>
        </div>
      )
    
    }
    export default Child;
    

    【讨论】:

    • 这将是 props.es6Function 而不是 this.props.es6Function
    • @SalmanShariati 如果我想从子组件调用父方法,使用功能/无状态组件而不是类。
    • @FerhiMalek 与您在调用它时只需在孩子的道具中传递父函数相同。在子组件中,您只需要指定您收到的道具参数
    【解决方案3】:

    您可以使用任何父方法。为此,您应该将此方法从您的父母发送给您的孩子,就像任何简单的值一样。您可以一次使用父级的多种方法。例如:

    var Parent = React.createClass({
        someMethod: function(value) {
            console.log("value from child", value)
        },
        someMethod2: function(value) {
            console.log("second method used", value)
        },
        render: function() {
          return (<Child someMethod={this.someMethod} someMethod2={this.someMethod2} />);
        }
    });
    

    并像这样在 Child 中使用它(用于任何操作或任何子方法):

    var Child = React.createClass({
        getInitialState: function() {
          return {
            value: 'bar'
          }
        },
        render: function() {
          return (<input type="text" value={this.state.value} onClick={this.props.someMethod} onChange={this.props.someMethod2} />);
        }
    });
    

    【讨论】:

    • 出色的答案。不知道你可以像这样将方法作为道具传递下去,我一直在使用 refs 来实现这一点!
    • 我得到了孩子要调用的回调,但是回调中的this.props变成了undefined
    • 您应该将此回调从父级发送到子级(尝试将此回调与this 绑定)
    • 嗨瓦伦丁·佩特科夫。欢迎!
    【解决方案4】:

    使用函数 ||无状态组件

    父组件

     import React from "react";
     import ChildComponent from "./childComponent";
    
     export default function Parent(){
    
     const handleParentFun = (value) =>{
       console.log("Call to Parent Component!",value);
     }
     return (<>
               This is Parent Component
               <ChildComponent 
                 handleParentFun={(value)=>{
                   console.log("your value -->",value);
                   handleParentFun(value);
                 }}
               />
            </>);
    }
    

    子组件

    import React from "react";
    
    
    export default function ChildComponent(props){
      return(
             <> This is Child Component 
              <button onClick={props.handleParentFun("YoureValue")}>
                Call to Parent Component Function
              </button>
             </>
            );
    }
    

    【讨论】:

    • 要为您的答案增加价值,请考虑添加有关此代码作用的简短说明。
    • 当你点击子组件中的按钮然后通过道具调用父组件函数。
    • 函数有参数怎么办?如何将参数传递给父级?
    • 是的! @alex351 我们可以处理这种情况。在子组件中 --> onClick={props.handleParentFun("YoureValue")} 在父组件中 --> handleParentFun={(value)=>{ console.log(); handleChildFun(值); }}
    • 我在点击按钮之前尝试了这个,它会在页面加载时自动调用该函数
    【解决方案5】:

    Parent 组件中的方法作为prop 传递给您的Child 组件。 即:

    export default class Parent extends Component {
      state = {
        word: ''
      }
    
      handleCall = () => {
        this.setState({ word: 'bar' })
      }
    
      render() {
        const { word } = this.state
        return <Child handler={this.handleCall} word={word} />
      }
    }
    
    const Child = ({ handler, word }) => (
    <span onClick={handler}>Foo{word}</span>
    )
    

    【讨论】:

      【解决方案6】:

      反应 16+

      子组件

      import React from 'react'
      
      class ChildComponent extends React.Component
      {
          constructor(props){
              super(props);       
          }
      
          render()
          {
              return <div>
                  <button onClick={()=>this.props.greetChild('child')}>Call parent Component</button>
              </div>
          }
      }
      
      export default ChildComponent;
      

      父组件

      import React from "react";
      import ChildComponent from "./childComponent";
      
      class MasterComponent extends React.Component
      {
          constructor(props)
          {
              super(props);
              this.state={
                  master:'master',
                  message:''
              }
              this.greetHandler=this.greetHandler.bind(this);
          }
      
          greetHandler(childName){
              if(typeof(childName)=='object')
              {
                  this.setState({            
                      message:`this is ${this.state.master}`
                  });
              }
              else
              {
                  this.setState({            
                      message:`this is ${childName}`
                  });
              }
      
          }
      
          render()
          {
              return <div>
                 <p> {this.state.message}</p>
                  <button onClick={this.greetHandler}>Click Me</button>
                  <ChildComponent greetChild={this.greetHandler}></ChildComponent>
              </div>
          }
      }
      export default  MasterComponent;
      

      【讨论】:

      • 很确定你的 Child 组件是一个 Class 组件,没有功能,我是 React 新手,所以如果我错了,请让我知道
      猜你喜欢
      • 2021-03-04
      • 2017-11-24
      • 2011-01-03
      • 2014-03-24
      • 2016-02-14
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 2019-11-21
      相关资源
      最近更新 更多