我正在尝试将onSelection
函数传递给组件:
const GenderScreen = (props) => {
const onSelection = () => {console.log('clicked')};
const buttons = ['one','two', 'three'];
const breadcrumb = `${i18n.t('stage 1')} > ${i18n.t('stage 2')} > ${i18n.t('stage 3')}`;
const sceneConfig = {
centredButtons: ['one','two', 'three'],
question: {
text: [breadcrumb, i18n.t('What is your ethnicity?')],
},
selectNumber: {},
onSelection: this.onSelection
};
return <SceneCentredButtons { ...props} sceneConfig={sceneConfig} />;
};
子组件:
const SceneCentredButtons = props => (
<LYDSceneContainer goBack={props.goBack} subSteps={props.subSteps}>
<Flexible>
<LYDSceneQuestion {...props.sceneConfig.question} />
<LYDCentredButtons
{...props.sceneConfig}
onSelection={props.sceneConfig.onSelection}
/>
</Flexible>
</LYDSceneContainer>
);
function LYDCentredButtons(props) {
const buttons = this.props;
return (
<View style={styles.main}>
{props.centredButtons.map((button, i) => {
const isLast = i + 1 === props.centredButtons.length;
const marginBottomStyle = !isLast && {
marginBottom: theme.utils.em(1.5),
};
return (
<LYDButton
style={[styles.button, marginBottomStyle]}
label={button.text}
onPress={() => props.onSelection(button.value)}
/>
);
})}
</View>
);
}
然而,当我的组件中出现错误时:
props.onSelection不是函数
如何在单击按钮时传递要使用的功能?
答案 0 :(得分:1)
GenderScreen
是无状态功能组件,您不需要使用this
关键字(这将是未定义的)。
而不是this.onSelection
使用onSelection
。
像这样:
const sceneConfig = {
centredButtons: ['one','two', 'three'],
question: {
text: [breadcrumb, i18n.t('What is your ethnicity?')],
},
selectNumber: {},
onSelection: onSelection
};