我在 React Native 中有一个 ScrollView,它有很多 View 。我使用以下代码存储要查看的 ref
cards.push(
<Card
ref={(ref) => {
console.log(ref);
this.cardRef[index] = ref;
ref.testMethod();
}} />
);
Card 是一个单独的组件,如下所示:
class Card extends Component {
constructor(props) {
super(props);
this.testMethod = this.testMethod.bind(this);
}
testMethod() {
console.log('this.is.test.method');
}
render() {
return (
<View style={styles.container}>
<Text>This.is.a.card</Text>
</View>
)
}
}
但是它说 testMethod 未定义,不能调用 ref.testMethod()。
最佳答案
我在 jsfiddle 上玩过你的代码,看起来调用了子方法:
var Card = React.createClass({
testMethod() {
console.log('this.is.test.method');
},
render() {
return (
<h1>this is a card.</h1>
)
}
});
var Parent = React.createClass({
render: function() {
return <div><Card ref={(r) => {r.testMethod()}}/></div>;
}
});
ReactDOM.render(
<Parent />,
document.getElementById('container')
);
关于javascript - react : Calling child component's method from parent component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34250702/