以下react组件具有四个按钮,这些按钮使用从父组件发送的道具中提取的数据创建。您可以在这里找到整个项目-> https://github.com/rajendrashenoy/myresume-react-app
可以通过-> https://rajendrashenoy.github.io/myresume-react-app/
访问该应用程序单击任何按钮时,它将单击的按钮的ID返回给父组件。我的问题是,如何突出显示单击的按钮?
import React, { Component } from 'react';
class ResumeTypes extends Component {
constructor(props) {
super(props);
//this.handleChange = this.handleChange.bind(this);
}
render() {
return this.props.resumetypes.map((resumetype, selectedtype) => (
<input type="button" style={{width: '25%', border: "none"}} id={resumetype.id} key={resumetype.id} value={ resumetype.type} onClick={this.props.selectedtype.bind(this, resumetype.id)}/>
));
}
}
答案 0 :(得分:0)
您应将当前选择的按钮保存在您的状态。 每次单击按钮ID时,用按钮ID刷新状态值。
然后根据您的按钮是否与状态中的选定值相对应,调整渲染函数中按钮的类:
class ResumeTypes extends React.Component {
constructor(props) {
super(props);
//this.handleChange = this.handleChange.bind(this);
this.state = {
selectedButton: null
}
}
buttonSelected = selectedButton => ev => {
this.setState({ selectedButton })
}
render() {
return (
<div>
{['A', 'B', 'C'].map(key =>
<button className={key === this.state.selectedButton ? 'selected' : ''} type="button" style={{ width: '25%', border: "none" }} key={key} onClick={this.buttonSelected(key)}>{key}</button>
)}
</div>
)
}
}
ReactDOM.render(<ResumeTypes />, document.getElementById("root"));
.selected {
border: 2px solid rgb(0, 0, 255);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.3.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.3.1/umd/react-dom.production.min.js"></script>
<div id='root'>
现在只需将您选择的CSS添加到按钮
答案 1 :(得分:0)
通过突出显示,我假设您希望更改按钮的背景颜色 因此,在onClick上,将活动标签的ID设置为状态,然后在className中有条件地添加活动类。
with Image(filename='rose:') as img:
img.resize(1,1)
with img[0, 0] as color:
r = math.ceil(255 * color.red)
g = math.ceil(255 * color.green)
b = math.ceil(255 * color.blue)
print('{0},{1},{2}'.format(r,g,b))
在Style.css
with Image(filename='rose:') as img:
img.resize(1,1)
with img[0, 0] as color:
r = color.red_int8
g = color.green_int8
b = color.blue_int8
print('{0},{1},{2}'.format(r,g,b))
答案 2 :(得分:0)
谢谢!您建议的代码有效,只添加了一点()
import React, { Component } from 'react';
class ResumeTypes extends Component {
constructor(props) {
super(props);
this.state = {ClickedButton: ''};
this.handleChange = this.handleChange.bind(this);
}
handleChange(id) {
this.setState({ClickedButton: id})
this.props.selectedtype.bind(this, id)()
}
render() {
return this.props.resumetypes.map((resumetype, selectedtype) => (
<input type="button"
className={resumetype.id === this.state.ClickedButton ? "App-Button-Active" : "App-Button-Default"}
style={{width: '25%', border: "none"}}
id={resumetype.id}
key={resumetype.id}
value={ resumetype.type}
onClick={ () => this.handleChange(resumetype.id)}/>
//onClick={this.props.selectedtype.bind(this, resumetype.id)}/>
));
}
}
export default ResumeTypes;