我正在try 将一个id从一个表组件(我正在使用ReactDataGrid库来呈现一个表)传递给父组件,这样我就可以在另一个子组件中使用它. 以下是我的父组件:

const CallForm = (props) => {
    const [isNewOpen, setIsNewOpen] = useState(false);
    const toggleNewPopup = () => {
        setIsNewOpen(!isNewOpen);
    }
    const [isEditOpen, setIsEditOpen] = useState(false);
    const toggleEditPopup = () => {
        setIsEditOpen(!isEditOpen);
    }
    return (
            <Table type={props.screenType === "taskScreen" ? "tasks" : "calls"} />//Trying to receive the id from here.//
            <div className="actions">
                <div className="buttons-actions">
                    <button onClick={toggleNewPopup}>{newCallText}</button>
                    {isNewOpen && <CallPopUp
                    state="add"
                    screenType={props.screenType}
                    handleClose={toggleNewPopup}
                    />}
                    <button onClick={toggleEditPopup}>{editCallText}</button>
                    {isEditOpen && <CallPopUp
                    state="edit"
                    id={}//Pass the id in here.//
                    screenType={props.screenType}
                    handleClose={toggleEditPopup}
                    />}
                    <button onClick={props.screenType === "taskScreen" ? closeTask : closeCall}> {closeCallText}</button>
                    <button onClick={props.screenType === "taskScreen" ? deleteTask : deleteCall}>{deleteCallText}</button>
                    <button onClick={props.screenType === "taskScreen" ? moveTask : moveCall}>{moveCallText}</button>
                </div>
                <div className="free-search">
                    <label htmlFor="freeSearch">Free Search</label>
                    <input type="text" name='freeSearch' id='freeSearch' />
                </div>
            </div>
}

这是表组件:

const Table = (props) => {
    const [elementId, setElementId] = useState("");
            return (
                <div>
                     <ReactDataGrid
                        idProperty='id'
                        columns={headers}
                        dataSource={allTasks}
                        theme='default-light'
                        rtl={true}
                        scrollThreshold={false}
                        enableColumnAutosize={true}
                        //Return the id to parent component.//
                    />
                    <div className='info'>{rowsText}</div>
                </div>
            )

这是CallPopUp组件:

const CallPopUp = (props) => {
  return (
      //Inputs including elements, in case of "edit" state the old data is shown in values.//
      //In order for me to call to the API get, put or delete request from server I need the id from the table element.//

我试着使用https://reactdatagrid.io/docs/的文档,我遇到了一些我认为可能会有帮助的解决方案,但我不知道如何使用它们. 例如: 来源:https://reactdatagrid.io/docs/api-reference#method-getItemAt

getItemAt
Fn(index)
Number
Returns the item at the specified index in the dataSource.

来源:https://reactdatagrid.io/docs/api-reference#method-getRowId

getRowId
Fn(index)
String|Number
Returns the id of the row at the specified index.

来源:https://reactdatagrid.io/docs/row-selection

Single row selection and keyboard navigation
Let's start with a simple example without support for selection. Try clicking the <ReactDataGrid /> below and then navigate with up/down keyboard arrows. Notice the currently active row changes as you hit arrow up/down. By default keyboard navigation is enabled, but you can turn it off by specifying enableKeyboardNavigation=false. You can also use home/end or page up/down to navigate the <ReactDataGrid /> rows. Additionally, when you move your mouse over a <ReactDataGrid /> row, it shows a hover state (this can be disabled by using showHoverRows=false).
Use activeIndex (controlled) or defaultActiveIndex (uncontrolled), combined with onActiveIndexChange to have full control on user navigation and the currently active row in the <ReactDataGrid />.
When using the controlled activeIndex prop and onActiveIndexChange callback prop to update the activeIndex, if you're doing other compute intensive stuff on the render function, you might notice some performance degradation in the scenario when the user keeps arrow up/down key pressed to quickly navigate to other records. If this is the case, it's better to use the uncontrolled defaultActiveIndex prop instead to obtain better performance.
When navigating the <ReactDataGrid /> with keyboard navigation, as the active index is updated, the <ReactDataGrid /> is automatically scrolled to show the currently active row in the viewport.

推荐答案

在您的父级中,定义一个useState来保存id:

const [elementId, setElementId] = useState("");

像这样将setElementId传递给子元素(这样子元素就可以更新elementId):

<Table type={props.screenType === "taskScreen" ? "tasks" : "calls"} setElementId={setElementId />

在您的子组件中添加onSelectionChange,然后在方法中调用props.SetElementId(data.id);:

const Table = (props) => {
  const onSelectionChange = useCallback(({data}) => {
    props.setElementId(data.id);
  }, [])

  return (
    <div>
      <ReactDataGrid
        idProperty="id"
        columns={headers}
        dataSource={allTasks}
        theme="default-light"
        rtl={true}
        scrollThreshold={false}
        enableColumnAutosize={true}
        onRowChange={onSelectionChange} // don't forget to attach it
      />
    </div>
  );
};

Reactjs相关问答推荐

有没有方法覆盖NextJS 14中的布局?

react 表复选框不对任何操作做出react

使用Reaction钩子窗体验证可选字段

React Context未正确更新

有没有可能在next.js和ssr中使用tsps?

在 Next13 中将 props 传递给 onClick 从服务器到客户端组件

在一个事件处理程序中进行多次调度是个好主意吗?

未处理的拒绝 (TypeError):无法读取未定义的属性(读取协议)

FlatList 不在 React Native 中呈现项目

在 React JS 中编辑表格数据

类型错误:类型typeof import(js-cookie)上不存在属性get

带有 webpack 错误多个文件匹配路由名称的 Expo-router.无法Bundle 或部署应用程序

为嵌套路由配置一个不存在的 url 的重定向

RTK 查询Mutations 在 StrictMode 中执行两次

NextJS htaccess 设置

antd 找不到 comments

为什么我在此代码段中看不到 useEffect for count = 1?

如果 URL 已随功能组件更改,则取消刷新

为什么 React 会多次调用我的应用程序的某些函数?

为什么重新渲染不会影响 setTimeout 的计数?