ReactJS 调用父方法 [英] ReactJS call parent method
问题描述
我正在 ReactJS 中迈出第一步,并试图了解父子之间的交流.我正在制作表单,所以我有样式字段的组件.而且我还有包含字段并检查它的父组件.示例:
var LoginField = React.createClass({渲染:函数(){返回 (<MyField icon="user_icon" placeholder="昵称"/>);},检查:函数(){控制台日志(aakmslkanslkc");}})var MyField = React.createClass({渲染:函数(){...},handleChange:函数(事件){//给父母打电话!}})
有什么办法吗.我的逻辑在reactjs世界"中是否良好?感谢您抽出宝贵时间.
2019 更新 react 16+ 和 ES6
发布此内容是因为 React.createClass
已从 React 16 版开始弃用,而新的 Javascript ES6 将为您带来更多好处.
家长
import React, {Component} from 'react';从./Child"导入孩子;导出默认类父级扩展组件{es6Function = (值) =>{控制台日志(值)}简化函数(值){控制台日志(值)}使成为 () {返回 (<div><孩子es6Function = {this.es6Function}简化函数 = {this.simplifiedFunction}/>
)}}
孩子
import React, {Component} from 'react';导出默认类子扩展组件{使成为 () {返回 (<div><h1 onClick= { () =>this.props.simplifiedFunction(<SomethingThatYouWantToPassIn>)}>某事</h1>
)}}
将无状态子节点简化为 ES6 常量
从'react'导入React;const Child = (props) =>{返回 (<div><h1 onClick= { () =>props.es6Function(<SomethingThatYouWantToPassIn>)}>某事</h1>
)}导出默认子项;
I'm making my first step in ReactJS and trying to understand communication between parent and children. I'm making form, so I have the component for styling fields. And also I have parent component that includes field and checking it. Example:
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!
}
})
Is there any way to do it. And is my logic is good in reactjs "world"? Thanks for your time.
2019 Update with react 16+ and ES6
Posting this since React.createClass
is deprecated from react version 16 and the new Javascript ES6 will give you more benefits.
Parent
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>
)
}
}
Child
import React, {Component} from 'react';
export default class Child extends Component {
render () {
return (
<div>
<h1 onClick= { () =>
this.props.simplifiedFunction(<SomethingThatYouWantToPassIn>)
}
> Something</h1>
</div>
)
}
}
Simplified stateless child as ES6 constant
import React from 'react';
const Child = (props) => {
return (
<div>
<h1 onClick= { () =>
props.es6Function(<SomethingThatYouWantToPassIn>)
}
> Something</h1>
</div>
)
}
export default Child;
这篇关于ReactJS 调用父方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!