React Hook: 将数据从子组件发送到父组件

我正在寻找将数据从子组件传递给其父组件的最简单的解决方案。

我听说过使用上下文,传递槽属性或更新道具,但我不知道哪一个是最好的解决方案。

我正在构建一个管理界面,包含一个 PageComponent,其中包含一个 ChildComponent 和一个表,我可以在其中选择多行。我想发送给我的父网页组件的行数,我已经选择了我的儿童组件。

差不多是这样:

网页内容:

<div className="App">
<EnhancedTable />
<h2>count 0</h2>
(count should be updated from child)
</div>

儿童组成部分:

 const EnhancedTable = () => {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Click me {count}
</button>
)
};

我相信这是一个非常简单的事情做,我不想使用 redux。

190677 次浏览

A common technique for these situations is to lift the state up to the first common ancestor of all the components that needs to use the state (i.e. the PageComponent in this case) and pass down the state and state-altering functions to the child components as props.

Example

const { useState } = React;


function PageComponent() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1)
}


return (
<div className="App">
<ChildComponent onClick={increment} count={count} />
<h2>count {count}</h2>
(count should be updated from child)
</div>
);
}


const ChildComponent = ({ onClick, count }) => {
return (
<button onClick={onClick}>
Click me {count}
</button>
)
};


ReactDOM.render(<PageComponent />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>


<div id="root"></div>

You can create a method in your parent component, pass it to child component and call it from props every time child's state changes, keeping the state in child component.

    const EnhancedTable = ({ parentCallback }) => {
const [count, setCount] = useState(0);
        

return (
<button onClick={() => {
const newValue = count + 1;
setCount(newValue);
parentCallback(newValue);
}}>
Click me {count}
</button>
)
};


class PageComponent extends React.Component {
callback = (count) => {
// do something with value in parent component, like save to state
}


render() {
return (
<div className="App">
<EnhancedTable parentCallback={this.callback} />
<h2>count 0</h2>
(count should be updated from child)
</div>
)
}
}

To make things super simple you can actually share state setters to children and now they have the access to set the state of its parent.

example: Assume there are 4 components as below,

function App() {
return (
<div className="App">
<GrandParent />
</div>
);
}


const GrandParent = () => {
const [name, setName] = useState("i'm Grand Parent");
return (
<>
<div>{name}</div>
<Parent setName={setName} />
</>
);
};


const Parent = params => {
return (
<>
<button onClick={() => params.setName("i'm from Parent")}>
from Parent
</button>
<Child setName={params.setName} />
</>
);
};


const Child = params => {
return (
<>
<button onClick={() => params.setName("i'm from Child")}>
from Child
</button>
</>
);
};

so grandparent component has the actual state and by sharing the setter method (setName) to parent and child, they get the access to change the state of the grandparent.

you can find the working code in below sandbox, https://codesandbox.io/embed/async-fire-kl197

I've had to deal with a similar issue, and found another approach, using an object to reference the states between different functions, and in the same file.

import React, { useState } from "react";


let myState = {};


const GrandParent = () => {
const [name, setName] = useState("i'm Grand Parent");
myState.name=name;
myState.setName=setName;
return (
<>
<div>{name}</div>
<Parent />
</>
);
};
export default GrandParent;


const Parent = () => {
return (
<>
<button onClick={() => myState.setName("i'm from Parent")}>
from Parent
</button>
<Child />
</>
);
};


const Child = () => {
return (
<>
<button onClick={() => myState.setName("i'm from Child")}>
from Child
</button>
</>
);
};

I had to do this in type script. The object-oriented aspect would need the dev to add this callback method as a field in the interface after inheriting from parent and the type of this prop would be Function. I found this cool!

Here's an another example of how we can pass state directly to the parent.

I modified a component example from react-select library which is a CreatableSelect component. The component was originally developed as class based component, I turned it into a functional component and changed state manipulation algorithm.

import React, {KeyboardEventHandler} from 'react';
import CreatableSelect from 'react-select/creatable';
import { ActionMeta, OnChangeValue } from 'react-select';


const MultiSelectTextInput = (props) => {
const components = {
DropdownIndicator: null,
};


interface Option {
readonly label: string;
readonly value: string;
}


const createOption = (label: string) => ({
label,
value: label,
});


const handleChange = (value: OnChangeValue<Option, true>, actionMeta: ActionMeta<Option>) => {
console.group('Value Changed');
console.log(value);
console.log(`action: ${actionMeta.action}`);
console.groupEnd();
props.setValue(value);
};


const handleInputChange = (inputValue: string) => {
props.setInputValue(inputValue);
};


const handleKeyDown: KeyboardEventHandler<HTMLDivElement> = (event) => {
if (!props.inputValue) return;


switch (event.key) {
case 'Enter':
case 'Tab':
console.group('Value Added');
console.log(props.value);
console.groupEnd();
props.setInputValue('');
props.setValue([...props.value, createOption(props.inputValue)])
event.preventDefault();
}
};


return (
<CreatableSelect
id={props.id}
instanceId={props.id}
className="w-100"
components={components}
inputValue={props.inputValue}
isClearable
isMulti
menuIsOpen={false}
onChange={handleChange}
onInputChange={handleInputChange}
onKeyDown={handleKeyDown}
placeholder="Type something and press enter..."
value={props.value}
/>
);
};


export default MultiSelectTextInput;

I call it from the pages of my next js project like this

import MultiSelectTextInput from "../components/Form/MultiSelect/MultiSelectTextInput";


const NcciLite = () => {
const [value, setValue] = useState<any>([]);
const [inputValue, setInputValue] = useState<any>('');


return (
<React.Fragment>
....
<div className="d-inline-flex col-md-9">
<MultiSelectTextInput
id="codes"
value={value}
setValue={setValue}
inputValue={inputValue}
setInputValue={setInputValue}
/>
</div>
...
</React.Fragment>
);
};

As seen, the component modifies the page's (parent page's) state in which it is called.

IF we Have Parent Class Component and Child function component this is how we going to access child component useStates hooks value :--

class parent extends Component() {
 

constructor(props){
super(props)
this.ChildComponentRef = React.createRef()
}
  

render(){
console.log(' check child stateValue: ',
this.ChildComponentRef.current.info);
return (<> <ChildComponent ref={this.ChildComponentRef} /> </>)
}
}

Child Component we would create using

React.forwardRef((props, ref) => (<></>))

. and

useImperativeHandle(ref, createHandle, [deps])

to customizes the instance value that is exposed to parent components

const childComponent = React.forwardRef((props, ref) => {
const [info, setInfo] = useState("")


useEffect(() => {
axios.get("someUrl").then((data)=>setInfo(data))
})


useImperativeHandle(ref, () => {
return {
info: info
}
})
return (<> <h2> Child Component <h2> </>)
})