该程序的本质是,当您在输入中输入任何值时,您将获得2个随机数和2个随机字符串。由于在输入数字期间值得使用onChange事件,因此必须对其进行更改和呈现。但是数字不会出现。但是,使用React Developer Tools,我看到了生成的值。
所有代码:
<html>
<head>
<meta charset="utf-8" />
<title>Page Title</title>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
class TextInput extends React.Component {
constructor(props) {
super(props);
this.state = {dropDownList: null};
this.eachRender = this.eachRender.bind(this);
}
eachRender() {
this.eachNumbers = [Math.random(0,10), Math.random(0,10)]; //Numbers are generated randomly
this.eachString = ["One random string", "Another random string"]; //Strings are also generated randomly, in order to simplify the code, they were given static values
var text = document.getElementById("text").value;
if (text !== ""){
this.setState({dropDownList: <DropDownList numbers = {this.eachNumbers} someString = {this.eachString}/>});
}
else this.setState({dropDownList: null});
}
render() {
return ( <div>
<input type="text" id="text" onChange={this.eachRender}>
</input>
{this.state.dropDownList}
</div> )
}
}
class DropDownList extends React.Component {
constructor(props) {
super(props);
this.eachTask = this.eachTask.bind(this);
this.state = { items: [ //The data should be presented as follows
{id: 1, item: this.props.numbers[0], href: this.props.someString[0]},
{id: 2, item: this.props.numbers[1], href: this.props.someString[1]},
] };
}
eachTask(items) {
return(
<li key = {items.id}>
Rund Number: <b>{items.item.toFixed(3)}</b> <br></br>
Rund String <b>{items.href}</b>
</li>
)
}
render() {
return(
<ul>
{this.state.items.map(this.eachTask)}
</ul>
)
}
}
ReactDOM.render(
<TextInput />, document.getElementById("app")
)
</script>
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script>
</body>
</html>
我认为问题与以下代码有关:
this.state = { items: [
{id: 1, item: this.props.numbers[0], href: this.props.someString[0]},
{id: 2, item: this.props.numbers[1], href: this.props.someString[1]},
] };
如何解决?
答案 0 :(得分:1)
如果要更改setState
的值,请使用this.state
。
切勿直接更改
this.state
,因为随后调用setState()
可能会替换您所做的更改。将此this.state视为不可变。
答案 1 :(得分:0)
对不起,我英语不好;
在DropDownList
中:直接渲染props
而不是state
;
它似乎确实在方法DropDownList
中创建了一个全新的eachRender
,但是唯一的区别是props
,您可以在控制台中打印它。
欢迎建议:)