reactjs - 从父组件触发子组件内部的函数
问题描述
如何以与抽屉导航相同的样式从父组件触发子组件内部的函数。
他们这样做:this.props.navigation.toggleDrawer();
来自父母
我该怎么做?
解决方案
如果我正确理解了您的问题,我认为您有点混淆了。您展示的示例是从子组件触发父组件功能的示例。
我将尝试通过 2 个示例来澄清一下。
1)从孩子触发:
要从子组件触发父组件的功能,您只需将该函数作为属性传递给子组件并在需要时运行它。
class Parent extends React.Component {
someFunction = (text) => {
console.log('Message from child: ', text);
}
render () {
return(
<Child someProperty={this.someFunction} />
)
}
}
class Child extends React.Component {
_onPress = () => {
// check if the property is defined and not null
if(this.props.someProperty) {
// run the function that is passed from the parent
this.props.someProperty();
}
}
render() {
return(
<Button onPress={this._onPress} title="Click Me"/>
)
}
}
2)从父母触发:
要从父组件触发子组件上的功能,您可以传递一个属性,该属性会在父组件上发生某些操作时更改。这将触发子组件中的重新渲染(在大多数情况下,有关更多信息,请查看shouldComponentUpdate
)。您可以检查属性更改,然后在子组件中执行您需要执行的操作。
class Parent extends React.Component {
state = {
someParameter: 'someInitialValue',
}
someFunction = (text) => {
this.setState({ someParameter: 'someValue' });
}
render () {
return(
<Child someProperty={this.state.someParameter} />
)
}
}
class Child extends React.Component {
someFunction = (text) => {
console.log('Message from parent: ', text);
}
componentDidUpdate(prevProps, prevState, snapshot) {
// Check if the suplied props is changed
if(prevProps.someProperty !== this.props.someProperty) {
// run the function with the suplied new property
this.someFunction(this.props.someProperty);
}
}
render() {
return(
{/* ... */}
)
}
}
推荐阅读
- visual-studio-code - 大写变量不再以不同颜色显示
- ios - 视图控制器中的依赖注入
- machine-learning - 如何多次训练 BigQuery ML 模型
- javascript - 无法让输入字段专注于点击
- hadoop - JPS 命令仅显示 JPS
- python - 多索引列 - 选择内部
- angular - 在 Angular 单元测试代码覆盖率报告中包含 HTML 文件
- installation - APIC 2018.210 OVA:将 Analytics 与网关关联时出现 URL 格式错误
- javascript - 访问 Laravel 从 Ajax 请求接收到的表单数据
- neo4j - Neo4j 中的索引 - 问题和疑问