当用户在react中单击按钮值时,我想存储它们,并将这些值存储在数组中以备后用。但是,基于我对REACT的基本了解,我遇到了错误,无法做到这一点。
我在首选项数组上使用console.log。但是我没有将值存储在首选项数组中。
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
getPreferences: false,
preferenceArray: []
};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
getPreferences: !state.getPreferences,
preferenceArray: state.preferenceArray.push(this.handleClick.value)
}));
render() {
const preference = this.state.preferenceArray;
console.log(preference[0]);
const { user } = this.props.auth;
const { profile, loading } = this.props.profile;
let dashboardContent;
if (profile == null || loading) {
dashboardContent = <Spinner />;
} else {
dashboardContent = (
<h2>
Select all issues that you are interested in:
<hr />
<br />
</h2>
);
}
return (
<div className="dashboard">
<div className="container">
<div className="row">
<div className="col-md-12">
<h1 className="display-4">Dashboard {dashboardContent}</h1>
<button
type="button"
name="Abortion"
value={this.state.name}
className="btn btn-secondary"
onClick={this.handleClick}
>
Abortion
</button>
<button
type="button"
name="GayMarriage"
value="Gay"
className="btn btn-secondary"
onClick={this.handleClick}
>
Gay Marriage
{" "}
</button>
<button
type="button"
name="Guns"
value="Guns"
className="btn btn-secondary"
onClick={this.handleClick}
>
Guns
{" "}
</button>
<button
type="button"
name="HIR"
value={this.state.name}
className="btn btn-secondary"
>
Higher Interest Rates
{" "}
onClick={this.handleClick}
</button>
</div>
</div>
</div>
</div>
);
}
}
答案 0 :(得分:1)
好吧,据我所知,您要做的基本上就是使用“事件”来获取值。
例如。
handleClick(e) {
//e- the event
this.setState(state => ({
getPreferences: !state.getPreferences,
preferenceArray: state.preferenceArray.push(e.target.value)// the event traget value
}));