使用React Bootstrap将数据传递到自定义元素

问题描述 投票:0回答:2

我有一个自定义样式的复选框,并且该复选框包含在一组映射的数据数组中。

{nfcArray && nfcArray.map((item, key) => {
     return (
          <tr class="hover">
             <td className="cell_style pl-3 pl-lg-5">
                <Row noGutters>
                    <Form.Check
                       required
                       name={item.cardId}
                       id={item.cardId}
                       as={customCheckBox}
                    />

                    <label>{item.cardId}</label>
                </Row>
            </td>
            <td className="cell_style pl-3 pl-lg-5">{item.name}</td>
          </tr>
      )

 })}

我的customCheckBox在render方法中给出,如下所示

        const customCheckBox = React.forwardRef(
            () => {

                return (
                    <div class="custom-control custom-checkbox my-1 pl-0" >
                        <input type="checkbox" className="custom-control-input" id="" />
                        <label className="custom-control-label" for=""></label>
                    </div>
                );
            },
        );

我想将item.cardId传递给我的自定义元素,因此我可以将item.cardId用作自定义元素中复选框输入的ID。我该怎么做?是否可以通过item.cardId

传递as={customCheckBox}
javascript reactjs react-bootstrap custom-element
2个回答
0
投票

将一个道具添加到您的customCheckBox之类的东西:

 const customCheckBox = React.forwardRef(
            () => {

                return (
                    <div class="custom-control custom-checkbox my-1 pl-0" >
                        <input type="checkbox" className="custom-control-input" 
                         id={props.itemId}/>
                        <label className="custom-control-label" for=""></label>
                    </div>
                );
            },
        );

现在您可以将itemId传递到父组件中的复选框

{nfcArray && nfcArray.map((item, key) => {
     return (
          <tr class="hover">
             <td className="cell_style pl-3 pl-lg-5">
                <Row noGutters>
                    <Form.Check
                       required
                       name={item.cardId}
                       id={item.cardId}
                    />
                     <customCheckBox itemId={item.cardId}/>

                    <label>{item.cardId}</label>
                </Row>
            </td>
            <td className="cell_style pl-3 pl-lg-5">{item.name}</td>
          </tr>
      )

 })}

0
投票

React-Bootstraps Form.CheckCheckInput Component未知的任何道具都将传递到您的customCheckBox Component。尝试使用cardId={item.cardId}之类的东西作为Form.Check的附加道具:

<Form.Check
   required
   name={item.cardId}
   id={item.cardId}
   as={customCheckBox}
   cardId={item.cardId} />
const customCheckBox = React.forwardRef((props) => {
    return (
        <div class="custom-control custom-checkbox my-1 pl-0" >
        <input type="checkbox" className="custom-control-input" id={props.cardId} />
        <label className="custom-control-label" for=""></label>
        </div>
    );
});
© www.soinside.com 2019 - 2024. All rights reserved.