反应本地改变儿童组成部分的状态
我想知道是否有一种方法可以使用函数从子组件中更新父函数组件中的状态组件,我认为我以错误的方式进行了
父母类别:
class Home extends Component {
state = {
year: '',
month: '',
day: '',
};
render() {
<Dropdown
label= {i18n.locale == 'en' ? 'Year' : 'سنة'}
data={years}
onSelect={() => this.setState(year)}/>
}
孩子组件:
const Dropdown = ({ label, data ,onSelect}) => {
const renderItem = ({ item }) => (
onSelect={() => this.setState(item )}
<TouchableOpacity style={styles.item} onPress={() => onItemPress(item)}>
<Text style={styles.buttonText}>{item}</Text>
</TouchableOpacity>
);
}
I am wondering if there is a way to update a state in a parent functional component from a child component using a function, i want to assign the value of {item}
in child component to the state in parent component, i think i did that in wrong way
the parent class components:
class Home extends Component {
state = {
year: '',
month: '',
day: '',
};
render() {
<Dropdown
label= {i18n.locale == 'en' ? 'Year' : 'سنة'}
data={years}
onSelect={() => this.setState(year)}/>
}
the child component:
const Dropdown = ({ label, data ,onSelect}) => {
const renderItem = ({ item }) => (
onSelect={() => this.setState(item )}
<TouchableOpacity style={styles.item} onPress={() => onItemPress(item)}>
<Text style={styles.buttonText}>{item}</Text>
</TouchableOpacity>
);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这样想:
OnSelect
将是您的父零件this.setState
与您的孩子组件之间的桥梁。为了做到这一点并保持灵活性,OnSelect应至少具有一个参数。从您拥有的东西来看,看起来您只需要下拉
才能更新年:现在,在您的孩子组件中,将OnSelect视为要更新父元中的年度值时要调用的函数:
同样出于好奇,是否有理由是父母组成的类别?
Think of it like this:
onSelect
will be the bridge between your parent componentthis.setState
and your child component. To do that and be flexible, onSelect should have at least one parameter. Judging from what you have, it looks like you only wantDropdown
to update year:Now in your child component think of onSelect as a function to call when it wants to update the year value in the parent component:
Also just out of curiosity, is there reason why the parent component is a class?