将数据从父组件传递到子 AccountsDropDown 时遇到问题。按照下面的代码,我可以将depositAcct参数传递给子级,但是不能传递给选定的值和onValueChnage方法。
因此,根据当前代码,这是目前面临的两个问题
这是我的父级组件
import React, { Component } from "react";
const transferType = ["Transfer", "Pay Loan"];
export default class a2aTransfer extends Component {
constructor(props) {
super(props);
this.state = {
mode: "start",
selectedTransferType: transferType[0],
fromAcct: "",
toAcct: "",
amt: "",
memo: ""
};
}
componentDidMount() {
this.setState({ fromAcct: this.context.depositAcct[0].desc });
this.setState({ toAcct: this.context.loanAcct[0].desc });
}
render() {
TransferForm = () => {
return (
<Container>
<Content>
<Form>
<View style={styles.item}>
<Text note>From Account</Text>
<AccountsDropDown
selectedValue={this.state.fromAcct}
depositAcct={this.context.depositAcct}
navigation={this.props.navigation}
onValueChange={itemValue => this.setState({ fromAcct: itemValue })}
/>
</View>
</Form>
</Content>
</Container>
);
};
if (this.state.mode == "start") {
return <TransferForm />;
}
return <TransferConfirm />;
}
}
a2aTransfer.contextType = MyContext;
这是我的孩子组成部分
import React, { Component } from "react";
import { Picker, Icon } from "native-base";
import { Dimensions, Platform } from "react-native";
export default class accountsDropDown extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Picker
selectedValue={this.props.selectedValue}
mode="dropdown"
iosHeader="Choose To Account"
style={{ width: Platform.OS === "ios" ? undefined : Dimensions.get("window").width }}
iosIcon={<Icon name="arrow-down" />}
onValueChange={() => this.props.onValueChange}
>
{typeof this.props.depositAcct != "undefined" &&
this.props.depositAcct.map((acct, idx) => {
return <Picker.Item key={idx} label={acct.desc} value={acct.masked} />;
})}
</Picker>
);
}
}
答案 0 :(得分:1)
onValueChange
是一个函数,因此您需要在子组件中使用以下值调用它:
<Picker
selectedValue={this.props.selectedValue}
mode="dropdown"
iosHeader="Choose To Account"
style={{ width: Platform.OS === "ios" ? undefined : Dimensions.get("window").width }}
iosIcon={<Icon name="arrow-down" />}
onValueChange={(value) => this.props.onValueChange(value)}
如果您不需要转换value
,则只需直接传递函数即可:
onValueChange={this.props.onValueChange}
答案 1 :(得分:0)
您已经编写了确定的代码,只需检查是否从上下文中获取数据即可。
在渲染方法中设置您的selectedValue并检查数据是否从上下文获取
render() {
console.log(this.props.selectedValue);
return (
<Picker
selectedValue={this.props.selectedValue}
mode="dropdown"
iosHeader="Choose To Account"
style={{ width: Platform.OS === "ios" ? undefined : Dimensions.get("window").width }}
iosIcon={<Icon name="arrow-down" />}
onValueChange={() => this.props.onValueChange}
>
{typeof this.props.depositAcct != "undefined" &&
this.props.depositAcct.map((acct, idx) => {
return <Picker.Item key={idx} label={acct.desc} value={acct.masked} />;
})}
</Picker>
);
}