gpt4 book ai didi

reactjs - 情感样式组件和 React.forwardRef 不能一起工作

转载 作者:行者123 更新时间:2023-12-04 13:01:48 24 4
gpt4 key购买 nike

我正在尝试编写两个 React 样式的组件(使用 Emotion 10),将一些自定义渲染逻辑指定到其中一个中,并保留检索它们的“引用”的能力。

这是我的代码:

const Foo = styled(props => <div {...props} />)`
color: red;
`;

// Here I **want** to use the component selector
// https://emotion.sh/docs/styled#targeting-another-emotion-component
const Bar = styled.div`
${Foo} {
background-color: yellow;
}
`;

const App = () => {
const ref = React.useRef();
return <Bar><Foo ref={ref}>foo</Foo></Bar>;
};

ReactDOM.render(<App />, document.body);

这段代码的问题是 React 抛出了这个警告:

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?



众所周知,情感风格的组件使用 React.forwardRef使开发人员能够使用 ref他们身上的属性(property)。但是一旦切换到自定义渲染方法,它似乎就不起作用了。

然后,如果我(尴尬地[1])将其转换为使用 React.forwardRef我得到的是:
const Foo = React.forwardRef((props, ref) => {
const Component = styled(props => <div {...props} />)`
color: red;
`;
return <Component {...props} ref={ref} />;
});

const Bar = styled.div`
${Foo} {
background-color: yellow;
}
`;

const App = () => {
const ref = React.useRef();
return <Bar><Foo ref={ref}>foo</Foo></Bar>;
};

ReactDOM.render(<App />, document.body);

但是,我得到了一个不同的错误:

TypeError: Cannot convert a Symbol value to a string



我尝试使用 ${Foo} 的地方正在发生这种情况.可能是因为 Emotion 需要一个样式组件,但我现在提供了一个 forwardRef成分。

这是一个 CodeSandbox,可以更轻松地使用我的代码:
https://codesandbox.io/s/7ylnlovlz6

那么,实现我想要的目标的正确方法是什么?

[1]:我知道在渲染中定义一个组件会使组件在每次渲染时重新渲染,但这在这种情况下无关紧要。

最佳答案

现在你不需要做任何事情。情绪正确处理 ref。
此代码将起作用。

const Foo = styled(props => <div {...props} />)`
color: red;
`;

const Bar = styled.div`
${Foo} {
background-color: yellow;
}
`;

const App = () => {
const ref = React.useRef();
return <Bar><Foo ref={ref}>foo</Foo></Bar>;
};

ReactDOM.render(<App />, document.body);

关于reactjs - 情感样式组件和 React.forwardRef 不能一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55343394/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com