我有3个具有不同值的单选按钮。我希望能够根据单击的单选按钮更改svg的填充颜色。现在,我有一个react组件,当单击单选按钮时,它会更新状态。但是,当我单击单选按钮时,没有任何颜色发生变化(填充值)。因此,我想知道是否有一种方法可以重新渲染对象,以使填充颜色根据单选按钮而改变?
class Chart extends Component {
constructor(props) {
super(props)
this.state = {
Time_01: '',
Time_02: '',
Time_03: '',
selectedOption: '',
windowHeight: 0,
windowWidth: 0,
rectFillColor: 'gray',
}
this.radioChange = this.radioChange.bind(this);
}
componentDidMount() {
this.setState({
windowWidth: Math.max(document.documentElement.clientWidth, window.innerWidth || 0),
windowHeight: Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
}, () => {
const svg = d3.select('.chart').append('svg')
.attr('height', this.state.windowHeight)
.attr('width', this.state.windowWidth)
.attr('id', 'svg-chart')
this.setState({ svg }, () => { this.draw(this.props) })
});
dataJson.rectFillColor = this.state.rectFillColor;
}
componentDidUpdate(prevProps, prevState) {
if (prevState.rectFillColor !== this.state.rectFillColor) {
dataJson.rectFillColor = this.state.rectFillColor;
}
}
radioChange(e) {
const selectedOption = e.currentTarget.value;
let radioButtonObj = {
TimeRadioTicked_01: false,
TimeRadioTicked_02: false,
TimeRadioTicked_03: false
}
if (selectedOption == 'Value Time') {
radioButtonObj.TimeRadioTicked_01 = true
radioButtonObj.TimeRadioTicked_02 = false
radioButtonObj.TimeRadioTicked_03 = false
} else if (selectedOption == 'Lead Time') {
radioButtonObj.TimeRadioTicked_01 = false
radioButtonObj.TimeRadioTicked_02 = true
radioButtonObj.TimeRadioTicked_03 = false
} else {
radioButtonObj.TimeRadioTicked_01 = false
radioButtonObj.TimeRadioTicked_02 = false
radioButtonObj.TimeRadioTicked_03 = true
}
this.changeColorOnClick(radioButtonObj);
this.setState({ selectedOption });
}
changeColorOnClick(buttonClicked) {
if (buttonClicked !== undefined) {
if (buttonClicked.valueTimeRadioTicked) {
this.setState({ rectFillColor: 'green' });
}
}
}
render() {
return (
<div>
<div>
<input type="radio"
value="Time_01"
checked={this.state.selectedOption === "Time_01"}
onChange={this.radioChange} /> Time_01
<input type="radio"
value="Time_02"
checked={this.state.selectedOption === "Time_02"}
onChange={this.radioChange} /> Time_02
<input type="radio"
value="Time_03"
checked={this.state.selectedOption === "Time_03"}
onChange={this.radioChange} /> Time_03
</div>
<div className="chart" />
</div>
);
}
}
包含D3矩形元素的单独JS文件
var data = [{ x: rectX, y: rectY,radioButtonSelect: selectedOption,
rectFillColor: dataJson.rectFillColor}]
var data = [{ x: rectX, y: rectY,
svg.append("rect")
.attr("x", (d) => { return d.x })
.attr("y", (d) => { return d.y })
.attr("width", 100)
.attr("height", 200)
.attr("fill", (d) => { return d.rectFillColor })
.attr("stroke", "gray")
.attr('rx', 3)
.attr('ry', 3)
.attr("cursor", "move");