【问题标题】:How to update a List of names when the UserClick on the name of the list he wants to update?当用户单击要更新的列表名称时如何更新名称列表?
【发布时间】:2022-12-18 13:13:21
【问题描述】:

大家好,我有一个这样的名字列表:

const footers = [
 title: 'fruits',
    description: 
    [
        
        'apple',
        'banana',
        'carrot',

 
    ]
]

然后我得到了这个:

<Grid container spacing={4} justifyContent="space-evenly">
          {footers.map((footer) => (
            <Grid item xs={6} sm={3} key={footer.title}>
              <Typography variant="h6" color="text.primary" gutterBottom>
                {footer.title}
              </Typography>
              <ul>
                {footer.description.map((item) => (
                  <li key={item}>
                    <button   variant="subtitle1" color="text.secondary"  >
                      {item}
                      </button>
                  </li>
                ))}
              </ul>
            </Grid>
          ))}
        </Grid>

上面的代码显示我的列表,其中每个值都有一个按钮。例如,当用户单击名称为 Carrot 的列表按钮时,如何让用户将其名称切换为新名称,如 tomato

【问题讨论】:

    标签: reactjs list button user-input onchange


    【解决方案1】:

    在这种情况下,您必须将 footers 定义为 React State 并在触发事件点击时更改项目。
    这是一个例子:

    const MyComponent = () => {
        const [footers, setFooters] = React.useState({
            title: 'fruits',
            description: 
            [
                
                'apple',
                'banana',
                'carrot',
            ]
        })
        const onClickName = (name) => event => {
            if(name === 'carrot'){
                setFooters(prev => {
                    const current = {...prev,
                        description: [...prev.description]
                    };
                    current.description[2] = 'tomato'
                })
                return;
            }
        }
        return (
            <Grid container spacing={4} justifyContent="space-evenly">
              {footers.map((footer) => (
                <Grid item xs={6} sm={3} key={footer.title}>
                  <Typography variant="h6" color="text.primary" gutterBottom>
                    {footer.title}
                  </Typography>
                  <ul>
                    {footer.description.map((item) => (
                      <li key={item}>
                        <button  variant="subtitle1" color="text.secondary"  onClick={onClickName(item)}>
                          {item}
                          </button>
                      </li>
                    ))}
                  </ul>
                </Grid>
              ))}
            </Grid>
        )
    }
    

    你应该看看这个State Hooks

    【讨论】:

      猜你喜欢
      • 2019-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多