我想将 Prop 从 App.js(父级)传递到 CommentItem.js(子级)再到 Button.js(子级的子级), 但是 Button,js(child of child) 的组件中的 props 是空的。
- App.js(父级)到 CommentItem.js(子级)
我推了mainuser: this.state.head
到 FlatList,并通过 renderItem={({ item }) => <CommentItem {...item}
传递 props(mainuser)
并且,CommentItem.js(child) 收到 mainuser
通过下面的代码。
const {
head,
text,
created,
mainuser,
subuser,
} =
- CommentItem.js(子级)到 Button.js(子级的子级)
我认为 props 是通过 传递给 Button 的, Button(child of child) 通过下面的代码接收到 props。
const {
mainuser,
} = this.props;
但是,Button.js 中的 props id 为空(子级的子级)。
# 我的代码有问题吗? 请问您能给点建议吗?
<小时/>App.js(父级)
export default class App extends Component<{}> {
constructor(props) {
super(props);
this.state = {
head: [],
list: [],
};
}
_onPress = (text) => {
const list = [].concat(this.state.list);
list.push({
key: Date.now(),
text: text,
done: false,
mainuser: this.state.head,
});
this.setState({
list,
});
}
render() {
const {
head,
list,
} = this.state;
var data = [["User1", "User2", "User3"],];
return (
<View style={styles.container}>
<View style={styles.dropdownHeader}>
<View style={styles.dropdown}>
<DropdownMenu
style={{flex: 1}}
bgColor={'white'}
tintColor={'#666666'}
activityTintColor={'green'}
handler={(selection, row) => this.setState({head: data[selection][row]})}
data={data}
>
</DropdownMenu>
</View>
</View>
<Text>To Do</Text>
<View style={styles.postinput}>
<CommentInput onPress={this._onPress} />
</View>
</View>
<View style={styles.CommentListContainer}>
<FlatList
/*inverted*/
style={styles.CommentList}
data={list}
renderItem={({ item }) => <CommentItem {...item} /> }
/>
</View>
);
}
}
CommentItem.js(子级)
const CommentItem = (props) => {
const {
head,
text,
created,
mainuser,
subuser,
} = props;
return (
<View style={styles.container}>
<View style={styles.left}>
<Text style={styles.text}>{text}</Text>
</View>
<View style={styles.function}>
<Button {...mainuser} />
</View>
</View>
);
}
Button.js(子的子)
export default class ApplauseButton extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
const {
mainuser,
} = this.props;
return (
<View style={styles.container}>
<Text>{mainuser}</Text>
</View>
);
}
}
最佳答案
如果您想访问mainuser
作为 Prop ,那么你必须将其传递为 <Button mainuser={mainuser} />
.
就目前情况而言,您是 spread ing mainuser
的内容.
关于javascript - 如何将 Prop 从父级传递给子级再到子级的子级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54683550/