reactjs - 在 react native 中将 props 传递给孩子
问题描述
我有两个组件。App 组件是父组件,Btn 组件是子组件。如何从 Btn 组件更改属性文本的值?
export default class App extends Component<Props> {
constructor() {
super();
this.text = 'testing';
this.onClicked = this.onClicked.bind(this);
}
onClicked() {
this.text = 'changed';
}
render() {
return (
<View style = { styles.container }>
<Text style = { styles.welcome }> { this.text } </Text>
<Btn />
</View>
);
}
}
class Btn extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Button
title = 'Button'
onPress = { ? }
/>
)
}
}
解决方案
您可以将父组件的 onClicked 函数作为 aprop
传递给子组件。
export default class App extends Component<Props> {
...
render() {
return (
<View style = { styles.container }>
<Text style = { styles.welcome }> { this.text } </Text>
<Btn onClicked={this.onClicked}/>
</View>
);
}
}
class Btn extends Component {
...
render() {
return (
<Button
title = 'Button'
onPress = {this.props.onClicked}
/>
)
}
}
推荐阅读
- c# - 注销并返回 Prism 应用程序中的登录屏幕
- c# - 隐藏 Windows.Forms.Listview 中的两个滚动条
- python - VS Code 的 Python 调试控制台中没有 Intellisense
- file - ASP.NET Core 中的任何 FileProvider 按文件夹而不是参数提供版本控制文件?
- excel - 为表 VBA 中的每个日期执行任务
- ruby-on-rails - 将文件夹上传到 Rails 中的 S3 存储桶
- javascript - 如何将一维向量与二维数组的元素进行比较
- java - PropertyReferenceException:找不到类型 SitePage 的属性 getOne
- blender - 如何将绿屏素材转换为 3d 对象
- python - 神经结构化学习中的“对抗性扰动”是什么意思?