Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

javascript - Dynamically creating and handling multiple togglebuttons in Reactjs using Material-ui ToggleButtons

I am trying to create a sidebar that has a dynamic amount of toggle buttons created from an object(keys,values). I can't seem to get the "key" value to change the corresponding "value" in my state. I am using @material-ui/lab/ToggleButton as my button components and I can retrieve the value selected but I can't find the index or value that's being changed. I created a sandbox for people to see the exact issue I am working with. I've tried looking in the html attributes(and creating my own), but I still am not able to get it. Even a suggestion to try some other way would be appreciated, though I'd like to see I am able to get it done with what I have already. Thank you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use inline function with a key param in the onClick handler:

import React, { useState } from "react";

import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ToggleButton from "@material-ui/lab/ToggleButton";
import ToggleButtonGroup from "@material-ui/lab/ToggleButtonGroup";

export default function MultipleToggleSelection() {
  const mylist = {
    a: "1",
    b: "1",
    c: "1",
    d: "1"
  };

  const [oneTwoThree, setOneTwoThree] = useState(mylist);

  const handleToggle = (key, value) => {
    oneTwoThree[key] = value;
    setOneTwoThree({...oneTwoThree});
  };

  return (
    <div>
      <div>{JSON.stringify(oneTwoThree, null, ' ')}</div>

      <List>
        {Object.keys(oneTwoThree).map((key, index) => (
          <ListItem key={key}>
            <ToggleButtonGroup
              value={oneTwoThree[index]}
              exclusive
              onChange={(event, value) => handleToggle(key, value)}
            >
              <ToggleButton value="1">1</ToggleButton>
              <ToggleButton value="2">2</ToggleButton>
              <ToggleButton value="3">3</ToggleButton>
            </ToggleButtonGroup>
            {key}
          </ListItem>
        ))}
      </List>
    </div>
  );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...