3 回答

TA貢獻1765條經(jīng)驗 獲得超5個贊
您可以使用任何父方法。為此,您應該像任何簡單值一樣,將此方法從您的父級發(fā)送給您的孩子。您可以一次使用父級的許多方法。例如:
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條經(jīng)驗 獲得超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常數(shù)的無狀態(tài)子級
import React from 'react';
const Child = () => {
return (
<div>
<h1 onClick= { () =>
this.props.es6Function(<SomethingThatYouWantToPassIn>)
}
> Something</h1>
</div>
)
}
export default Child;
添加回答
舉報