你需要使用一个变量,比如
props
例如,作为参数
constructor
功能。然后把它传给
super
. 下面的代码修复了所有警告。
class List extends React.Component {
constructor(props) {
super(props);
this.tag = props.tag;
this.attributes = props.attributes;
this.items = props.items;
}
render() {
return React.createElement(
this.props.tag,
this.props.attributes,
items.map(
(n, i) =>
new React.createElement(ListItem, {
attributes: { ...n.attributes, key: i },
value: n.value
})
)
);
}
}
class ListItem extends React.Component {
constructor(props) {
super(props);
this.attributes = props.attributes;
this.value = props.value;
}
render() {
return React.createElement("li", this.props.attributes, this.props.value);
}
}
const items = [
{ attributes: null, value: "A" },
{ attributes: null, value: "B" },
{ attributes: null, value: "C" },
{ attributes: null, value: "D" },
{ attributes: null, value: "E" }
];
const root = document.getElementById("root");
ReactDOM.render(
new React.createElement(List, { tag: "ul", attributes: null, items }),
root
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Official doc
说
类组件应始终使用
道具
.
当我看到
source
:
const hasMutatedProps = instance.props !== newProps;
warningWithoutStack(
instance.props === undefined || !hasMutatedProps,
'%s(...): When calling super() in `%s`, make sure to pass ' +
"up the same props that your component's constructor was passed.",
name,
name,
);
它似乎反应检查
道具
在中接收到的对象
构造函数
函数与使用传递给基类的对象相同
super()
或者没有。在你的代码中,它当然是不一样的。你要传递给
super({attributes, value})
例如,完全不同的对象。因为在JS:
{a: 1, b: 2} === {a:1, b:2} // false
{a: 1, b: 2} !== {a:1, b:2} // true