传递函数作为道具

时间:2017-07-18 13:00:12

标签: reactjs

我正在尝试将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不是函数

如何在单击按钮时传递要使用的功能?

1 个答案:

答案 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
};