如何创建表格,以用户从reactjs表单中获取输入
我制作了一个表单和饼图,但对如何从表单访问数据一无所知
chartData:{
datasets:[{
data:[10,20,30,40,50]
}]
}
我希望通过表格形式的输入来创建图表
答案 0 :(得分:1)
使用以下代码将生成动态图表
import React, { Component } from "react";
import { Pie } from "react-chartjs-2";
export default class App extends Component {
state = {
dataPie: {
datasets: [{
data: [10, 20, 30]
}],
},
first: "",
second: "",
}
handleSubmit = () => {
const { dataPie } = this.state;
this.setState({
dataPie: {
...dataPie,
datasets: [{
...dataPie.datasets,
data: [
this.state.first,
this.state.second
]
}]
}
})
}
handleChange = (evt) => {
let a = parseInt(evt.target.value)
this.setState({
[evt.target.name]: a,
})
}
render() {
const { data, dataPie } = this.state;
console.log(dataPie);
return (
<React.Fragment>
<input type="number"
value={this.state.first}
name="first"
onChange={(evt) => this.handleChange(evt)} />
<input type="number"
value={this.state.second}
name="second" onChange={(evt) => this.handleChange(evt)} />
<button onClick={() => this.handleSubmit()}>add data to chart</button>
<h1>pie chart</h1>
<Pie data={dataPie} />
</React.Fragment>
)
}
}
答案 1 :(得分:1)
export default class App extends Component {
state = {
dataPie: {
datasets: [{
data: [10, 20, 30]
}],
},
first: "",
second: "",
}
handleSubmit = () => {
const { dataPie } = this.state;
this.setState({
dataPie: {
...dataPie,
datasets: [{
...dataPie.datasets,
data: [...dataPie.datasets[0].data,
this.state.first, this.state.second]
}]
}
})
}
handleChange = (evt) => {
let a = parseInt(evt.target.value)
this.setState({
[evt.target.name]: a,
})
}
render() {
const { data, dataPie } = this.state;
console.log(dataPie);
return (
<React.Fragment>
<input type="number"
value={this.state.first}
name="first"
onChange={(evt) => this.handleChange(evt)} />
<input type="number"
value={this.state.second}
name="second" onChange={(evt) => this.handleChange(evt)} />
<button onClick={() => this.handleSubmit()}>add data to chart</button>
<h1>pie chart</h1>
<Pie data={dataPie} />
</React.Fragment>
)
}
}
答案 2 :(得分:0)
数据:[... dataPie.datasets [0] .data,this.state.first,this.state.second]}] change this to
数据:[this.state.first,this.state。秒]}]