2
我想從列表中獲得一個隨機物品。 到目前爲止,我設法把我的列表放在一個數組中,我試圖讓我需要的一個函數的項目,但我需要它的地方,它是未定義的! 我不知道我錯在哪裏!從屬性物品列表中獲得隨機物品通過反應js
我想看到的結果,在這個控制檯日誌
handleChange(event) {
this.setState({value: event.target.value});
var NewDictionary = this.Dictionary;
console.log(Rand(NewDictionary));
}
整個代碼是在這裏:
class Application extends React.Component{
constructor(props) {
super(props);
this.state = {
value:'option2',
button:'submit',
};
this.Dictionary = {
Salam:"Hi",
khodafez:"Bye",
are: "Yes",
na: "No",
shab: "Night",
rooz: "Day",
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
var NewDictionary = this.Dictionary;
console.log(Rand(NewDictionary));
}
handleSubmit(event) {
this.setState({button: this.state.value});
event.preventDefault();
}
render(){
return(
<form onSubmit={this.handleSubmit}>
<div> {this.Dictionary.Salam} </div>
<div className="radio">
<label>
<input type="radio" value={this.Dictionary.Salam}
checked={this.state.value === this.Dictionary.Salam}
onChange={this.handleChange} />
{this.Dictionary.Salam}
</label>
</div>
<div className="radio">
<label>
<input type="radio" value="option2"
checked={this.state.value === 'option2'}
onChange={this.handleChange} />
Option 2
</label>
</div>
<div className="radio">
<label>
<input type="radio" value="option3"
checked={this.state.value === 'option3'}
onChange={this.handleChange} />
Option 3
</label>
</div>
<div className="radio">
<label>
<input type="radio" value="option4"
checked={this.state.value === 'option4'}
onChange={this.handleChange} />
Option 4
</label>
</div>
<button onClick={this.handleSubmit} className="btn btn-default" type="submit">{this.state.button}</button>
</form>
)
}
}
function Rand(NewDictionary){
let i = NewDictionary.length - 1;
const j = Math.floor(Math.random() * i);
return NewDictionary[j];
}
ReactDOM.render(
<Application />,
document.getElementById('root')
);
'this.Dictionary'是一個對象,而不是一個數組。 –
你的字典是一個對象,而不是一個數組。使用'Object.keys(NewDictionary)'來獲取其數組。 –