Rah*_*ore 9 javascript reactjs
有没有办法从存储在变量中的 React 元素中获取文本内容而无需引用?
有一个功能组件,它接收titleprop,其中包含 React 元素:
function component({ title }) {
const content = title.textContent() // Need Something like this
}
Run Code Online (Sandbox Code Playgroud)
这个title道具可能有像这样的反应节点:<div>Some Title</div>。但我只想在渲染之前获取变量中节点的内容。是否可以?
当我 console.logtitle变量时,这是输出,我想要的内容在props.children数组内部,那么有没有一种方法可以在不遍历键的情况下获取它:
Arj*_*jan 18
我还没有找到比遍历对象来获取文本更好的解决方案。在打字稿中:
/**
* Traverse any props.children to get their combined text content.
*
* This does not add whitespace for readability: `<p>Hello <em>world</em>!</p>`
* yields `Hello world!` as expected, but `<p>Hello</p><p>world</p>` returns
* `Helloworld`, just like https://mdn.io/Node/textContent does.
*
* NOTE: This may be very dependent on the internals of React.
*/
function textContent(elem: React.ReactElement | string): string {
if (!elem) {
return '';
}
if (typeof elem === 'string') {
return elem;
}
// Debugging for basic content shows that props.children, if any, is either a
// ReactElement, or a string, or an Array with any combination. Like for
// `<p>Hello <em>world</em>!</p>`:
//
// $$typeof: Symbol(react.element)
// type: "p"
// props:
// children:
// - "Hello "
// - $$typeof: Symbol(react.element)
// type: "em"
// props:
// children: "world"
// - "!"
const children = elem.props && elem.props.children;
if (children instanceof Array) {
return children.map(textContent).join('');
}
return textContent(children);
}
Run Code Online (Sandbox Code Playgroud)
我不太喜欢这样,希望有更好的解决方案。
| 归档时间: |
|
| 查看次数: |
14721 次 |
| 最近记录: |