React 使用 ref 访问 innerhtml

问题描述 投票:0回答:0

我无法使用 refs 访问我的元素的内部 html。我的元素的 ref 被输出,但是 element.innerHTML 被输出为未定义,这是为什么?

const MyEditableComponent = ({ content }) => {
  const valueRef = useRef();

  const onContentChange = React.useCallback(evt => {
    const sanitizeConf = {
      allowedTags: ["b", "i", "a", "p"],
      allowedAttributes: {
        a: ["href"]
      }
    };
    const innerhtml = valueRef.current.innerHTML;
    console.log(valueRef.current)
    console.log(innerhtml)
    //setContent(sanitizeHtml(innerhtml, sanitizeConf))    
  }, [])

  return (
    <ContentEditable 
        ref = {valueRef}
        html={content}//inner html
        onChange={onContentChange}
        tagName="div"             
        style={{ overflowWrap: 'break-word', wordWrap: 'break-word', wordBreak: 'break-word', whiteSpace: 'pre-wrap', overflow: 'auto'
        }}
    />
  )
}

我可以用更好的方式写这个吗?

reactjs react-hooks ref
© www.soinside.com 2019 - 2024. All rights reserved.