ReactJS调用父方法

时间:2014-10-03 09:29:09

标签: 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!
    }
})

有没有办法做到这一点。我的逻辑是好的反应世界&#34;?谢谢你的时间。

6 个答案:

答案 0 :(得分:127)

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

例如:

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使用Childvalue属性调用onChange。返回Child会将onChange处理程序绑定到标准<input />元素,如果已定义,则将值传递给Parent的回调。

结果调用了Parent的{​​{1}}方法,第一个参数是changeHandler<input />字段的字符串值。结果是,Child的状态可以使用该值更新,导致父{q}个元素在Parent的输入字段中输入时使用新值更新

答案 1 :(得分:36)

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

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} />);
    }
});

答案 2 :(得分:15)

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>
        )
    }
}

将无状态子级简化为SE6常量

import React from 'react';

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

}
export default Child;

答案 3 :(得分:2)

使用功能||无状态组件

父组件

 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>
         </>
        );
}

答案 4 :(得分:1)

将方法从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>
)

答案 5 :(得分:0)

反应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;