[英]Set React Context inside function-only component
My goal is very simple.我的目标很简单。 I am just looking to set my react context from within a reusable function-only (stateless?) react component.
我只是想从一个可重用的纯函数(无状态?)反应组件中设置我的反应上下文。
When this reusable function gets called it will set the context (state inside) to values i provide.当这个可重用的 function 被调用时,它会将上下文(内部状态)设置为我提供的值。 The problem is of course you can't import react inside a function-only component and hence I cannot set the context throughout my app.
问题当然是您不能在仅功能组件中导入 react,因此我无法在整个应用程序中设置上下文。
There's nothing really to show its a simple problem.没有什么可以真正表明它是一个简单的问题。
But just in case:但以防万一:
<button onCLick={() => PlaySong()}></button>
export function PlaySong() {
const {currentSong, setCurrentSong} = useContext(StoreContext) //cannot call useContext in this component
}
If i use a regular react component, i cannot call this function onClick:如果我使用常规反应组件,我不能调用这个 function onClick:
export default function PlaySong() {
const {currentSong, setCurrentSong} = useContext(StoreContext) //fine
}
But:但:
<button onCLick={() => <PlaySong />}></button> //not an executable function
One solution: I know i can easily solve this problem by simply creating a Playbtn component and place that in every song so it plays the song.一个解决方案:我知道我可以通过简单地创建一个 Playbtn 组件并将其放置在每首歌曲中以便它播放歌曲来轻松解决这个问题。 The problem with this approach is that i am using a react-player library so i cannot place a Playbtn component in there...
这种方法的问题是我正在使用一个 react-player 库,所以我不能在其中放置一个 Playbtn 组件......
You're so close!你这么近! You just need to define the callback inside the function component.
您只需要在 function 组件内定义回调。
export const PlaySongButton = ({...props}) => {
const {setCurrentSong} = useContext(StoreContext);
const playSong = () => {
setCurrentSong("some song");
}
return (
<button
{...props}
onClick={() => playSong()}
/>
)
}
If you want greater re-usability, you can create custom hooks to consume your context.如果您想要更高的可重用性,您可以创建自定义挂钩来使用您的上下文。 Of course where you use these still has to follow the rules of hooks .
当然你在哪里使用这些还是要遵守hooks 的规则。
export const useSetCurrentSong = (song) => {
const {setCurrentSong} = useContext(StoreContext);
setCurrentSong(song);
}
It is possible to trigger a hook function by rendering a component, but you cannot call a component like you are trying to do.可以通过渲染组件来触发钩子 function,但您不能像尝试那样调用组件。
const PlaySong = () => {
const {setCurrentSong} = useContext(StoreContext);
useEffect( () => {
setCurrentSong("some song");
}, []
}
return null;
}
const MyComponent = () => {
const [shouldPlay, setShouldPlay] = useState(false);
return (
<>
<button onClick={() => setShouldPlay(true)}>Play</button>
{shouldPlay && <PlaySong />}
</>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.