我正在开发我的第一个应用程序,并且仍在学习流程。 所以假设我有一个组件叫做:
持有方法 HelloWorld() 的父级,如下例所示:
import React, { Component } from 'react';
class Parent extends Component {
Helloworld() {
console.log('Hello world');
}
render () {
return (
<View>{this.props.children}</View>
)
}
}
module.exports = Parent;
然后我想将它导入另一个组件并使用它的方法,那么我该怎么做呢? 我会写另一个简短的例子来说明我将如何实现它。
import React, { Component } from 'react';
import { Parent } from 'path to parent';
//or
const Parent = require('path to parent');
//which of these is better?
class Home extends Component {
Helloworld() {
console.log('Hello world');
}
render () {
return (
<Parent>
// this is what i need
<Button onClick={parent.Helloword()}>Some Button</Button>
</Parent>
)
}
}
module.exports = Home;
在此先感谢您的帮助。
最佳答案
通常你应该通过 Prop 将信息从 parent 传递给 child 。
parent.jsx:
import Child from './child';
class Parent extends Component {
constructor(props) {
super(props);
this.helloWorld = this.helloWorld.bind(this);
}
helloWorld() {
console.log('Hello world!');
}
render() {
return (
<View><Child method={this.helloWorld} /></View>
);
}
}
child.jsx:
class Child extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Button onClick={this.props.method} />
);
}
}
编辑:关于 import
和 require
之间的偏好,我相信这是一个品味问题,但我认为 import
更干净。
关于javascript - 从子组件调用父组件的方法 - React Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38650992/