我试图显示一个作为属性存储在另一个类中的类。
这是主要的上层阶级:
updatable_number.jsx
import React, { Component } from 'react';
import SimpleNumber from "./simple_number.jsx"
import SimpleNumberUpdater from "./simple_number_updater.jsx"
export default class UpdatableNumber extends Component {
constructor(props) {
super(props);
this.state = {
number_value: this.props.value
};
this.number = <SimpleNumber value={this.state.number_value}/>;
this.updater = <SimpleNumberUpdater target={this.number}/>;
console.log(this.number);
console.log(this.updater);
this.render = this.render.bind(this);
}
render () {
// note that if I do `this.number` instead of `this.updater`, it works
return (
<div>
<div>
{this.updater}
</div>
</div>
);
}
}
但是,执行此操作时出现错误Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {isMounted, enqueueSetState, enqueueReplaceState, enqueueForceUpdate}). If you meant to render a collection of children, use an array instead.
这对我来说很奇怪,因为当我用this.number
做完全相同的事情时,它工作得很好,可以正确显示数字。
如何在渲染功能中显示updater
?
这里有simple_number_updater.jsx
和simple_number.jsx
,以防万一:
simple_number_updater.jsx
import React, { Component } from 'react';
export default class SimpleNumberUpdater extends Component {
constructor (props) {
super(props);
this.state = {
target: this.props.target
};
this.handle_increment = this.handle_increment.bind(this);
this.render = this.render.bind(this);
}
handle_increment () {
this.target.setState({ value: this.target.state.value + 1});
}
render () {
return (
<div>
<button onClick={ this.handle_increment }>Increment</button>
</div>
);
}
}
simple_number.jsx
import React, { Component } from 'react';
export default class SimpleNumber extends Component {
constructor(props) {
super(props);
this.state = {
value: this.props.value
};
this.render = this.render.bind(this);
}
render () {
return (
<div>
<span className="primary">{this.state.value}</span>
</div>
);
}
}
答案 0 :(得分:0)
好吧,如果我了解得很好,就想对增量按钮进行模块化,我认为您应该查看自己的反应模式,因为您在this
对象中投入了很多,而应该使用state如果要创建一个可重用的组件,只需将其导出,然后将要重用的变量作为道具传递,如下所示:
还请注意,通过导出和导入按钮,您已经可以直接在渲染器中使用它,如下所示:
import React, { Component } from 'react';
import SimpleNumber from "./simple_number.jsx"
import SimpleNumberUpdater from "./simple_number_updater.jsx"
export default class UpdatableNumber extends Component {
state = { // in recent React version you can remove the constructor
// and just put your value inside the business_logic part of your component
number_value: this.props.value
}
render () {
return (
<div>
<div>
<SimpleNumber hereAProps={this.state.someState}/>
<SimpleNumberUpdater hereAnotherProps={this.state.someState} />
</div>
</div>
);
}
}
我的建议: -审查状态 -复习父母与子女之间的道具交流 然后再出手