2 回答
TA贡献1850条经验 获得超11个赞
您发布的代码没有问题,如下所示
class Child extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>{this.props.noOfSides}</h1>
<h1>{this.props.noOfDice}</h1>
</div>
);
}
}
class NoOfDice extends React.Component {
constructor(props) {
super(props);
this.state = { mystate: 1 };
}
render() {
return (
<div>
<h1>Number of Dice</h1>
<h2>{this.state.mystate}</h2>
<Child noOfDice={this.state.mystate} /> //error is
in this line
</div>
);
}
}
ReactDOM.render(<NoOfDice />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
TA贡献1803条经验 获得超3个赞
Child 期望 noOfDice 作为道具,这就是为什么它在一种情况下而不是另一种情况下工作的原因。您应该保持名称不变。我已将您的代码编辑为 prop 名称为acceptedNumber. 还要检查子组件是否已正确导入。
尝试这个:
// NoOfSides
class NoOfSides extends React.Component {
constructor(props) {
super(props);
this.state = { mystate: 6 };
}
render() {
return (<div>
<h1>Number of Sides</h1>
<h2 >
{this.state.mystate}
</h2>
<Child acceptedNumber={this.state.mystate} />
</div>
);
}
};
// NoOfDice
class NoOfDice extends React.Component {
constructor(props) {
super(props);
this.state = { mystate: 1 };
}
render() {
return (<div>
<h1>Number of Dice</h1>
<h2 >
{this.state.mystate}
</h2>
<Child acceptedNumber={this.state.mystate} />
</div>
);
}
};
// Child
class Child extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>{this.props.acceptedNumber}</h1>
</div>
)
}
}
添加回答
举报