简体   繁体   中英

how to send id to refs(forwardrefs) to children components

I have 4 buttons and submit button, upon clicking on submit button, i need to add effects or button focus to 4 buttons based on pattern like [2,4,3,1], the buttons should animate like this pattern upon submit button click. Here's what i have tried, I am unable to send id using refs. how do i send id to refs or how do i animate buttons based on refs or any other on how to add effects to children components.

constructor(props) {
    super(props);
    this.state = {
      values: [
        { id: 1, color: "blue" },
        { id: 2, color: "red" },
        { id: 3, color: "green" },
        { id: 4, color: "yellow" }
      ]
    };
    this.myRef = React.createRef();
  }

   getvalue = (id, ref) => {
     console.log(ref);
   };
in render ` const { values } = this.state;`

         <div className="col-md-12">
            {values.map(value => (
              <Card
                ref={this.myRef}
                key={value.id}
                value={value}
                id={value.id}
                onbtnclick={() => this.getvalue(value.id)}
              />
            ))}
          </div>

child component

const Card = React.forwardRef((props, ref) => {
  return (
    <button
      ref={ref}
      key={props.id}
      className="btn newcard m-2 active"
      aria-pressed="true"
      onClick={() => this.props.onbtnclick(props.id, ref)}
      style={{ background: `${props.value.color}` }}
    />
  );
});
const ref = React.createRef;

i create a Sand Box for you here the Example https://codesandbox.io/s/xenodochial-flower-cl52b

u need to use useImperativeHandle of React Hooks plus Forward Refs

/// ------------- here is the refactor Sand Box you mentioned in Comments https://codesandbox.io/s/amazing-germain-ww7yi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM