从节点中提取文本有点麻烦。
节点是一个段落。
<p className="Blend" refs="hello"> { `${this.state.landing}?utm_campaign=${this.state.utm}` } </p>
Run Code Online (Sandbox Code Playgroud)
我正在尝试在函数中将节点的内容记录到控制台。
makeSmall = () => {
var text = this.refs.hello.innerText
console.log(text)
}
Run Code Online (Sandbox Code Playgroud)
但是,此控制台不返回任何内容。我也尝试通过 className 访问节点。
在 React 中访问文本的正确方法是什么?
const getNodeText = node => {\n if ([\'string\', \'number\'].includes(typeof node)) return node\n if (node instanceof Array) return node.map(getNodeText).join(\'\')\n if (typeof node === \'object\' &&\xc2\xa0node) return getNodeText(node.props.children)\n}\n\nconst printHTML = ref => ref && (ref.innerText = document.querySelector(\'h1\').outerHTML)\nRun Code Online (Sandbox Code Playgroud)\n\nhttps://codesandbox.io/s/react-getnodetext-h21ss
\n\n // in the picture\n {heading} // <Heading>Hello <span className="red">Code</span>Sandbox</Heading>\n <pre ref={printHTML}/>\n <pre>{getNodeText(heading)}</pre>\nRun Code Online (Sandbox Code Playgroud)\n\n最初来自这里/sf/answers/4239523431/
\n感谢大家的贡献。我之前的方法有一些错误。
即,尝试在函数中设置引用。以下是我为使其发挥作用而采取的步骤。
1) 使用 React.createRef() 构造 ref;(React 16 中的新功能)
class Newone extends Component {
state = {
allocation: "Acq",
};
textUrl = React.createRef();
Run Code Online (Sandbox Code Playgroud)
2)将ref附加到适当的节点
<p className="Blend" ref={this.textUrl}> { `${this.state.landing}?utm_campaign=${this.state.utm}` } </p>
Run Code Online (Sandbox Code Playgroud)
3)使用 value.innertext 引用 ref
handleLinkClick = (event) => {
bitly.shorten(this.textUrl.value.innerText)
Run Code Online (Sandbox Code Playgroud)
**确保您使用的是 React 版本 16.3.0-alpha.1。
以下是控制台的屏幕截图。
bitly.shorten(this.textUrl.value)

bitly.shorten(this.textUrl.value.innerText)

如果您只想返回节点中的文本,请确保附加innerText。
希望这可以帮助
| 归档时间: |
|
| 查看次数: |
9422 次 |
| 最近记录: |