如何在单击方法中更改项目的字体重量 – React

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

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

const App = () => ( 
); class GroceryListItem extends React.Component{ constructor(props){ super(props); } render(){ return (
); } } 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 (
    { this.props.groceryItems.map(item =>
  • {item}
  • ) }
); } }

知道为什么这不起作用以及如何解决它? PS。 关于如何改进我的代码的建议表示赞赏。

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

 class GroceryList extends React.Component { constructor(props){ super(props); this.state = { selected: null }; } onClickItem (item) { this.setState({ selected: item }) } render(){ return ( 
    { this.props.groceryItems.map(item =>
  • {item}
  • ) }
) } }

将css变量存储在状态中并在onClick上更改

 import React from 'react'; import ReactDOM from 'react-dom'; const App = () => ( 
); class GroceryListItem extends React.Component{ constructor(props){ super(props); } render(){ return (
); } } 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 (
    { this.props.groceryItems.map(item => { {console.log(this.state.style[item],"this.state")} return (
  • {item}
  • ) }) }
); } } ReactDOM.render(, document.getElementById('root'));