[英]How to pass the props from parent to child to child of child?
我想将道具从App.js(父)传递到CommentItem.js(child)到Button.js(child的孩子),但是在Button,js(child的孩子)的组件中道具是空的。
我将mainuser: this.state.head
推mainuser: this.state.head
FlatList,然后通过renderItem={({ item }) => <CommentItem {...item}
并且,CommentItem.js(child)通过以下代码接收了mainuser
。
const {
head,
text,
created,
mainuser,
subuser,
} =
我以为道具是由粘贴到Button的,而Button(child的孩子)通过以下代码接收了道具。
const {
mainuser,
} = this.props;
但是,道具id在Button.js(child的子代)中为空。
#我的代码有问题吗? 你能给点建议吗?
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
,则必须将其作为<Button mainuser={mainuser} />
。
就目前而言,您正在传播 mainuser
的内容。
根据您的代码,主要用户似乎是数组,
this.state = {
head: [],//array
list: [],
};
....
list.push({
key: Date.now(),
text: text,
done: false,
mainuser: this.state.head,// main user should be array
});
所以你也需要在<Button />
道具名称
像这样
<Button mainuser={mainuser} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.