[英]React - Objects are not valid as a React child when creating array of JSX components
我正在将一个项目从旧的React.createComponent
为新的ES6类定义。 我有以下组成部分:
class AnswerFrame extends React.Component {
constructor(props) {
super(props);
}
render() {
var props = this.props;
var selectedNumbers = props.selectedNumbers.map(function (i) {
return (
<span onClick={props.unselectNumber.bind(null, i)}>
{i}
</span>
)
});
return (
<div id="answer-frame">
<div className="well">
{selectedNumbers}
</div>
</div>
);
}
};
这个想法是定义一个数组selectedNumbers
,它是一个跨度数组,每个跨度都有一个onclick事件。 然后渲染这些。
这段代码在转换为ES6之前运行良好,但现在却出现以下错误:
Error: Objects are not valid as a React child
(found: object with keys {dispatchConfig, _targetInst, nativeEvent, type, target, currentTarget, eventPhase, bubbles, cancelable, timeStamp, defaultPrevented, isTrusted, view, detail, screenX, screenY, clientX, clientY, ctrlKey, shiftKey, altKey, metaKey, getModifierState, button, buttons, relatedTarget, pageX, pageY, isDefaultPrevented, isPropagationStopped, _dispatchListeners, _dispatchInstances}).
If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `AnswerFrame`.
为什么这不再起作用了?
是的,问题出在props.selectedNumbers
。 试图弄清楚方式的改变this
当您使用势必ES6
,我从代码绑定其他地方取出空。
这个:
numbers.push(
<div className={className} onClick={selectNumber.bind(i)}>
{i}
</div>
);
应该是
numbers.push(
<div className={className} onClick={selectNumber.bind(null,i)}>
{i}
</div>
);
因此props.selectedNumbers
是导致问题的对象。
在react props中进行绑定是一种不好的做法( https://daveceddia.com/avoid-bind-when-passing-props/ ),请考虑将selectNumber设置为高阶函数:
const selectNumber = (i) => () => {
// your original function code here
doWhateverWith(i);
}
并将onClick设置为:
<div className={className} onClick={selectNumber(i)}>
我知道这只是做同一件事的另一种方式,但是...
members.push(
<div className={className} onClick={() => {selectedNumber(i);}}>
{i}
</div>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.