ReactJS调用父方法

Kar*_*toR 120 javascript reactjs

我正在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!
    }
})
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点.我的逻辑在反应世界中是好的吗?谢谢你的时间.

Mik*_*ver 139

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

例如:

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} />
        );
    }
});
Run Code Online (Sandbox Code Playgroud)

在上述示例中,Parent调用Child与的特性valueonChange.的Child回报结合一个onChange处理程序,以一个标准的<input />元件,并传递值到Parent如果它定义的回调函数.

作为结果,ParentchangeHandler方法被调用的第一个参数是从所述字符串值<input />的字段Child.结果是Parent可以使用该值更新状态,导致父<span />元素在Child输入字段中键入时使用新值进行更新.

  • @ o01不,你没有,因为我正在使用自动绑定所有组件方法的`React.createClass`.如果我使用的是React es6类,那么你需要绑定它(除非你在构造函数中自动绑定,这是很多人现在正在做的事情来解决这个问题) (18认同)
  • 我认为你需要绑定父函数,然后再将其传递给子节点:`<Child value = {this.state.value} onChange = {this.changeHandler.bind(this)} />` (14认同)

Vit*_*hyn 42

您可以使用任何父方法.为此,您应该将此方法从您的父级发送给您的孩子,就像任何简单的值一样.并且您可以同时使用父项中的许多方法.例如:

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} />);
    }
});
Run Code Online (Sandbox Code Playgroud)

并像这样使用它进入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} />);
    }
});
Run Code Online (Sandbox Code Playgroud)


Fan*_*ing 28

使用react 16+和ES6进行2019更新

发布此React.createClass版本已从反应版本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>
    )
  }

}
Run Code Online (Sandbox Code Playgroud)

儿童

import React, {Component} from 'react';

export default class Child extends Component {

  render () {
  return (
    <div>
    <h1 onClick= { () =>
            this.props.simplifiedFunction(<SomethingThatYouWantToPassIn>)
          }
        > Something</h1>
    </div>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

简化无国籍儿童为SE6常数

import React from 'react';

const Child = () => {
  return (
    <div>
    <h1 onClick= { () =>
        this.props.es6Function(<SomethingThatYouWantToPassIn>)
      }
      > Something</h1>
    </div>
  )

}
export default Child;
Run Code Online (Sandbox Code Playgroud)


Omk*_*war 6

使用函数 || 无状态组件

父组件

 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);
             }}
           />
        </>);
}
Run Code Online (Sandbox Code Playgroud)

子组件

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>
         </>
        );
}
Run Code Online (Sandbox Code Playgroud)