【发布时间】:2020-12-13 03:14:47
【问题描述】:
当我尝试将我的函数传递给子组件时出现此错误: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>
)
}
...
【问题讨论】:
-
_renderAnswerInputs可能还需要在构造函数中绑定到this。不能肯定地说,但要验证您可以在_renderAnswerInputs函数中控制台记录this.replaceVariables。如果它未定义那是你的问题。 -
@BrianThompson 我只是像
this._renderAnswerInputs = this._renderAnswerInputs.bind(this)一样绑定它,但仍然遇到同样的错误 -
好的,你控制台记录了那个方法中的函数吗?这将缩小您的调试搜索范围,以了解它是否在那里定义(或未以某种方式定义为函数)
-
@BrianThompson 是的,这就是日志显示的内容:
function () { [native code] }。我认为这个问题在某种程度上与 MultipleChoiceType 是函数有关,而不是一个类...... -
怀疑它与函数与类有关。我在这里找不到任何明显错误的地方。还有其他相关代码吗?你能做一个可运行的例子吗?
标签: javascript reactjs components react-props