我是js
和reactjs
的新手。我正在尝试创建一个ButtonGroup
,内部只有少量Buttons
,希望当我单击特定的Button
(在ButtonGroup
中)时,只有该特定的按钮会突出显示(更改颜色),其余部分将恢复正常颜色。
以下是执行上述行为的代码,但是在setColour
方法中,我遇到了错误_this.state.selected.props is undefined
。有人可以指出我哪里出问题了吗?另外,如果有人可以告诉我这是否是解决此问题的正确方法。
import React from "react"
import {
ButtonGroup,
Button
} from "reactstrap"
class MainButtonsGroup extends React.Component {
constructor (props) {
super(props)
this.state = {
selected: null
}
}
handleSelection = (e) => {
this.setState({selected: e.target})
}
setColour = (key) => {
if (this.state.selected)
{
// ERROR : _this.state.selected.props is undefined
return (this.state.selected.props.key === key) ? 'primary' : 'secondary'
}
}
render() {
return (
<ButtonGroup>
<Button key={1} onClick={this.handleSelection} color={this.setColour(1)}>MainButtonA</Button>
<Button key={2} onClick={this.handleSelection} color={this.setColour(2)}>MainButtonB</Button>
<Button key={3} onClick={this.handleSelection} color={this.setColour(3)}>MainButtonC</Button>
</ButtonGroup>
)
}
}
export default MainButtonsGroup;
答案 0 :(得分:2)
您不应该坚持使用e.target参考,您必须在控制台中收到有关它的React警告吗?您刚刚在应用中创建了内存泄漏。
相反,从目标复制您需要的内容,然后将引用作为垃圾回收。尽管在您的情况下,无需将数据附加到DOM节点:
<Button onClick={() => this.handleSelection(this.setColour(3))}>MainButtonC</Button>
请注意,除非您要在循环中映射元素,否则不需要key={3}
。
handleSelection = (color) => {
this.setState({ selected: color })
}
但是这段代码有点奇怪,只需记录一下单击按钮的索引并为其提供样式设置类即可,例如
class MainButtonsGroup extends React.Component {
state = {
selectedIndex: null,
}
handleSelection = (index) => {
this.setState({selectedIndex: index})
}
render() {
const idx = this.state.selectedIndex;
return (
<ButtonGroup>
<Button className={idx === 1 ? 'primary' : 'secondary'} onClick={() => this.handleSelection(1)}>MainButtonA</Button>
<Button className={idx === 2 ? 'primary' : 'secondary'} onClick={() => this.handleSelection(2)}>MainButtonB</Button>
<Button className={idx === 3 ? 'primary' : 'secondary'} onClick={() => this.handleSelection(3)}>MainButtonC</Button>
</ButtonGroup>
);
}
}
答案 1 :(得分:2)
您无法从DOM节点获得组件的道具。相反,您可以将按钮名称保留在组件状态的数组中,并使用该名称在render方法中呈现按钮。
然后可以将按钮名称传递给handleSelection
,并将其用作您的selected
值。如果您的按钮是选中的按钮,则可以使用primary
颜色,否则可以使用secondary
颜色。
示例
import React from "react";
import ReactDOM from "react-dom";
import { ButtonGroup, Button } from "reactstrap";
import "bootstrap/dist/css/bootstrap.min.css";
class MainButtonsGroup extends React.Component {
constructor(props) {
super(props);
this.state = {
buttons: ["A", "B", "C"],
selected: null
};
}
handleSelection = button => {
this.setState({ selected: button });
};
render() {
const { buttons, selected } = this.state;
return (
<ButtonGroup>
{buttons.map(button => (
<Button
key={button}
onClick={() => this.handleSelection(button)}
color={selected === button ? "primary" : "secondary"}
>
MainButton{button}
</Button>
))}
</ButtonGroup>
);
}
}