reactjs - 如何将父状态传递给子组件
问题描述
基本上,我被困在将父母的组件状态传递给孩子。我有一个具有动态内容偏移侦听器的父组件,因此如果我向下或向上滚动,它会使用此偏移值更新状态。我还有一个子组件,在该子组件内我有另一个子组件(以便更轻松地浏览代码)。
那是父组件。我检查并在滚动发生时更新状态。
constructor(props) {
super(props);
this.state = {
contentOffset: 1
}
this.onScrollEvent = this.onScrollEvent.bind(this);
}
onScrollEvent = event => {
this.setState(
{
contentOffset: event.nativeEvent.contentOffset.y,
}
)
}
render() {
return (
<ScrollView
showsVerticalScrollIndicator={false}
onScroll={this.onScrollEvent.bind(this)>
<ChildOne
animation={this.state.contentOffset}/>
);
}
子组件
constructor(props) {
super(props);
}
render() {
return (
<NestedChild
handleClick={this.openSettingsInHeader}
header="What the..."
transformAnimation={this.props.animation}/>
);
}
Child的子组件
constructor(props) {
super(props);
this.state = {
AnimatedTextValue: new Animated.Value(0),
ProfileOffset: this.props.transformAnimation
}
}
render() {
const animatedStyles = {
transform: [
{ scale: 0 }]} //how to link the AnimatedTextValue to ProfileOffset?
return (
<Animated.Text style={[styles.nameStyle,animatedStyles]}>Hi!</Animated.Text>
);
}
我需要传递状态来为该孩子的子组件内的组件设置动画。
解决方案
将道具传递transformAnimation
给转换{ scale: this.props.transformAnimation }
Child的子组件
render() {
const animatedStyles = {
transform: [
{ scale: this.props.transformAnimation }]} // <<====
return (
<Animated.Text style={[styles.nameStyle,animatedStyles]}>Hi!</Animated.Text>
);
}
并从状态 ProfileOffset 中删除您不需要的状态。每次进行更改时,您都会从父母那里获得价值的道具。
this.state = {
AnimatedTextValue: new Animated.Value(0),
ProfileOffset: this.props.transformAnimation // <==== remove this
}
推荐阅读
- jquery - 如何从javascript中的变量的选择中获取值
- flutter - Flutter:如何从 Cloud Firestore 的数组数据字段中获取数据?
- sap-fiori - 自定义 OData 服务在 iOS SAP Cloud Platform 应用程序上缺少属性
- synchronization - vkCmdPipelineBarrier 澄清渲染通道同步范围
- python - Python TypeError:“int”对象在 OOP 中不可调用
- amazon-web-services - AWS - 获取与用户 ID 关联的电子邮件
- python - 尽管安装了 pandas,但我无法在 PyCharm 上使用 Pandas 读取任何 CSV 文件
- indexing - 在 Excel 中查找满足多个条件的匹配项
- php - php 从数组到日期累计添加数字
- sql-server - 针对同一个表结果的外部应用(和交叉应用)