我在下面有一个 react 代码,我在一个杂货列表数组中进行迭代。我创建了一个状态更改和一个样式变量,单击时一次仅更改一项。
但是它没有起作用。由于某种原因,当我单击一个项目时,所有项目都会变成粗体。
const App = () => (
<div><GroceryListItem /></div>
);
class GroceryListItem extends React.Component{
constructor(props){
super(props);
}
render(){
return (
<div><GroceryList groceryItems={['Cucumber', 'Kale']}/></div>
);
}
}
class GroceryList extends React.Component {
constructor(props){
super(props);
this.state = {
done: false
};
}
onClickItem(){
this.setState({
done: !this.state.done
});
}
render(){
var style = {
fontWeight: this.state.done ? 'bold' : 'normal'
};
return (
<ul>
{
this.props.groceryItems.map(item => <li style={style} onClick={this.onClickItem.bind(this)} key={item}>{item}</li>)
}
</ul>
);
}
}
知道为什么这不起作用以及如何修复它吗? 附言。感谢有关如何改进我的代码的建议。
最佳答案
将 css 变量存储在状态中并在 onClick 时更改
import React from 'react';
import ReactDOM from 'react-dom';
const App = () => (
<div><GroceryListItem /></div>
);
class GroceryListItem extends React.Component{
constructor(props){
super(props);
}
render(){
return (
<div><GroceryList groceryItems={['Cucumber', 'Kale']}/></div>
);
}
}
class GroceryList extends React.Component {
constructor(props){
super(props);
this.state = {
done: false,
style: "normal"
};
}
onClickItem(item){
let style = {
[item]: "bold"
}
this.setState({
done: !this.state.done,
style: style
},() => {});
}
render(){
return (
<ul>
{
this.props.groceryItems.map(item => {
{console.log(this.state.style[item],"this.state")}
return (<li style={{fontWeight: this.state.style[item] || "normal"}} id={item} onClick={this.onClickItem.bind(this,item)} key={item}>{item}</li>
)
})
}
</ul>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
关于javascript - 如何在单击方法中更改项目的字体粗细 - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48615887/