将函数传递给子组件时出现错误

时间:2020-08-24 13:10:22

标签: javascript reactjs components react-props

当我尝试将函数传递给子组件时,出现此错误:TypeError: props.replaceVariables is not a function我缺少什么吗?据我所知,我正确地传递了我的功能。所以我无法解决问题是否在Player.js或MultipleChoiceType.js中。 我的父母组件:

class Player extends React.Component {

    constructor(props) {
        super(props);
        this.replaceVariables = this.replaceVariables.bind(this);
    }

    state = {
        scope: {},
        variables: this.props.question.data.variables,
        ...
    }

    _renderAnswerInputs(part, partIndex) {
        switch (part.questionType) {
          case Constants.PartMultipleChoiseQuestionType:
            return part.solutions.map((solution, solutionIndex) => {
              return <MultipleChoiceType
                replaceVariables={this.replaceVariables}
                choices={solution[0].choices}
                playerAnswer={this.state.myAnswerPartData?.answers[0]}
                selectedChoiceChanged={(choiceIndex) => this.onChangedMyMultipleChoise(solution[0].choices[choiceIndex], solutionIndex)}
                edit={false} />
            })
        }
    }

    replaceVariables(q) {
        for (var key in this.state.scope) {
          q = this.replaceAll(q, '<span class="mord">' + key + '</span>', '<span class="mord mathdefault">' + this.state.scope[key] + '</span>');
          q = this.replaceAll(q, '<span class="mord mtight">' + key + '</span>', '<span class="mord mathdefault">' + this.state.scope[key] + '</span>');
        };
        return q;
    }
}
...

我的孩子组件:

function MultipleChoiceType(props) {
    const dispatch = useDispatch()
    return (
        <div>
            {
                props.choices?.map((choice, cIndex) => (
                    <div style={{ display: 'flex', padding: 5 }} key={cIndex}>
                        <div dangerouslySetInnerHTML={{ __html: props.replaceVariables(choice.value) }} />
                    </div>
                ))
            }
        </div>
    )
}
...

2 个答案:

答案 0 :(得分:1)

我尝试复制相同的行为,并且运行良好。

https://stackblitz.com/edit/react-fx2gso?file=src%2FApp.js

肯定是其他原因导致了此问题。

答案 1 :(得分:-1)

使用=>箭头函数,则无需在构造函数中绑定函数 尝试将值与功能绑定

编辑=>尝试使用箭头函数代替旧语法

   code        value
0  VC_1  LTC Limited
1  VC_1  LTC Limited
2  BN_3      AMZ ENT
3  BN_4     BBM CROP