ReactJS调用父方法

我正在React React中迈出第一步,并试图理解父母与孩子之间的交流。我正在制作表单,所以我具有用于样式字段的组件。而且我还有包含字段并对其进行检查的父组件。例:


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“ world”上好吗?谢谢你的时间。


手掌心
浏览 797回答 3
3回答

POPMUISE

您可以使用任何父方法。为此,您应该像任何简单值一样,将此方法从您的父级发送给您的孩子。您可以一次使用父级的许多方法。例如:var Parent = React.createClass({&nbsp; &nbsp; someMethod: function(value) {&nbsp; &nbsp; &nbsp; &nbsp; console.log("value from child", value)&nbsp; &nbsp; },&nbsp; &nbsp; someMethod2: function(value) {&nbsp; &nbsp; &nbsp; &nbsp; console.log("second method used", value)&nbsp; &nbsp; },&nbsp; &nbsp; render: function() {&nbsp; &nbsp; &nbsp; return (<Child someMethod={this.someMethod} someMethod2={this.someMethod2} />);&nbsp; &nbsp; }});并将其像这样用于Child(用于任何操作或任何子方法):var Child = React.createClass({&nbsp; &nbsp; getInitialState: function() {&nbsp; &nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; value: 'bar'&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; },&nbsp; &nbsp; render: function() {&nbsp; &nbsp; &nbsp; return (<input type="text" value={this.state.value} onClick={this.props.someMethod} onChange={this.props.someMethod2} />);&nbsp; &nbsp; }});

智慧大石

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 {&nbsp; es6Function = (value) => {&nbsp; &nbsp; console.log(value)&nbsp; }&nbsp; simplifiedFunction (value) {&nbsp; &nbsp; console.log(value)&nbsp; }&nbsp; render () {&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; <Child&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; es6Function = {this.es6Function}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; simplifiedFunction = {this.simplifiedFunction}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; </div>&nbsp; &nbsp; )&nbsp; }}儿童import React, {Component} from 'react';export default class Child extends Component {&nbsp; render () {&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; <h1 onClick= { () =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.props.simplifiedFunction(<SomethingThatYouWantToPassIn>)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; > Something</h1>&nbsp; &nbsp; </div>&nbsp; &nbsp; )&nbsp; }}简化为SE6常数的无状态子级import React from 'react';const Child = () => {&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; <h1 onClick= { () =>&nbsp; &nbsp; &nbsp; &nbsp; this.props.es6Function(<SomethingThatYouWantToPassIn>)&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; > Something</h1>&nbsp; &nbsp; </div>&nbsp; )}export default Child;
打开App,查看更多内容
随时随地看视频慕课网APP