【发布时间】:2020-03-09 20:14:53
【问题描述】:
我试图让 React 从一个从 dialog.json 文件映射的 Button 组件中获取 id。在浏览器中检查时,该 ID 正确位于 Button 标记中。但我不确定如何在点击时抓住它。
(onClick 抓取id 后,会更新State 并从下一个dialog.json 呈现Text 和Buttons)
import React, { Component } from 'react';
import API from '../../utils/API';
import './style.css';
import dialog from './dialog.json';
import Button from '../../components/Button';
import Text from '../../components/Text';
class Game extends Component {
state = {
userID: "", //user logged in
currentLine: dialog[0]
}
handleClick = () => {
alert('Your next Line is: ' + this.id);
console.log(dialog[0]);
this.setState({
currentLine: dialog[this.id]
})
}
componentDidMount() {
API.getMyDude(this.props.username).then(myDude => {
this.setState({
userID: myDude
})
})
// this.startGame();
}
render() {
return (
<div>
<br />
<br />
{/* {console.log(textNodes[0])} */}
< Text text={this.state.currentLine.text} />
<br />
< div >
{this.state.currentLine.options.map(option => (
// console.log(option.nextText),
< Button
option={option.text}
id={option.nextText}
handleClick={this.handleClick}
/>
))}
</div >
</div >
)
}
}
export default Game
此外,欢迎提供任何其他提示或技巧!
【问题讨论】:
标签: javascript reactjs components setstate