如何在单击方法中更改项目的字体权重 - React [英] How can I change the fontweight of an item at click method - React

查看:99
本文介绍了如何在单击方法中更改项目的字体权重 - React的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面有一个反应代码,我在一个购物清单列表中进行迭代。我创建了一个状态更改和一个样式变量,它在单击时一次只能更改一个项目。

I have a react code below where I iterate over in an array of grocery list. I created a state change and a style variable that will change only one item at a time when clicked.

然而它不起作用。出于某种原因,当我点击一个项目时,它会将所有项目都变为粗体。

However it did not work. For some reason when I click on one item it turns all of them bold.

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>

   );
  }
}

任何想法为什么这不起作用以及如何解决它?
PS。关于如何改进我的代码的建议值得赞赏。

Any idea why is this not working and how to fix it? PS. Suggestions on how to improve my code is appreciated.

推荐答案

您正在更改状态onClick,并更改可访问的样式变量到完整的渲染功能。您只需要知道点击了哪个元素并将其存储在您的状态中。您可以尝试以下方法。

You are changing the state onClick, and changing the style variable which is accessible to the complete render function. You just need to know which of the element is clicked and store it in your state. You can try the below method.

class GroceryList extends React.Component {
constructor(props){
  super(props);
  this.state = {
    selected: null
  };
}

onClickItem (item) {
  this.setState({
    selected: item
  })
}

render(){
return (
       <ul>
       {
        this.props.groceryItems.map(item => <li style={{'fontWeight': this.state.selected === item ? 'bold' : 'normal'}} onClick={this.onClickItem.bind(this, item)} key={item}>{item}</li>)
       }
    </ul>
)
}
}

这篇关于如何在单击方法中更改项目的字体权重 - React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆