3 回答
TA贡献1765条经验 获得超5个赞
您可以使用任何父方法。为此,您应该像任何简单值一样,将此方法从您的父级发送给您的孩子。您可以一次使用父级的许多方法。例如:
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} />);
}
});
TA贡献1946条经验 获得超3个赞
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;
添加回答
举报