【问题标题】:Passing data to Reactstrap modal将数据传递给 Reactstrap 模式
【发布时间】:2020-12-01 13:37:40
【问题描述】:

我的申请中有一些类别。对于每个类别,我想添加一些图像。所以我在 reactstrap 中添加了一个 Modal 来显示一个模态窗口来添加一些文件和描述。到目前为止一切都很好。但是当我单击启动模式按钮(在此处添加文件)时出现问题,我无法将 id 传递给 Modal。我尝试使用 useState 钩子为变量设置一个值,但只有在模式关闭后它才会获得一个值。

我的姓名缩写像

const [categories, setCategories] = useState([])
const [categoryId, setCategoryId] = useState()
const [modal, setModal] = useState(false)

const toggle = (id) => {
    setCategoryId(id)
    setModal(!modal);
}

然后是显示类别的代码

{ categories.map( cat => (
    <div className="card border-0 rounded-0 img-thumbnail">
        <img src={'assets/images/image_upload.jpg'} value={t._id} className="img-thumbnail" onClick={()=>toggle(cat._id)} alt="..."/>
    </div>               
)) }

<Modal 
    isOpen={modal} 
    toggle={toggle} 
    centered={true}
>
    <ModalBody>
        <div className="p-2">
            <form>
                <div className="form-group">
                    <input type="file" className="form-control-file" id="exampleFormControlFile1"/>
                </div>
                <div className="form-group">
                    <input type="text" className="form-control" id="exampleInputPassword1" placeholder="Caption Title"/>
                </div>
                <div className="form-group">
                    <textarea className="form-control" placeholder="Description" id="exampleFormControlTextarea1" rows="3"></textarea>
                </div>
                <button type="submit" className="btn btn-form">Upload</button>
                <span onClick={toggle} style={{cursor: 'pointer'}} className="ml-2 btn btn-form-outline">Cancel</span>
            </form>
        </div>
    </ModalBody>
</Modal>

只有在模式关闭后我才能获得类别 ID。我怎样才能将值与模态窗口一起设置????

【问题讨论】:

    标签: javascript reactjs react-props reactstrap


    【解决方案1】:

    这里的问题是toggle 在模式打开和关闭时也会被调用。如果模态应该关闭或打开并在单独的调用中设置id,您可以使用toggle 函数专门用于设置状态。

    const toggle = () => {
        // setCategoryId(id) // remove this
        setModal(!modal);
    }
    
    <img onClick={()=>{toggle(); setCategoryId(cat._id)}} />
    

    【讨论】:

      猜你喜欢
      • 2013-07-21
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 2017-08-23
      • 2023-03-05
      • 2014-11-13
      相关资源
      最近更新 更多