如何创建一个react元素并对其应用javascript方法

时间:2018-12-13 18:29:46

标签: javascript html reactjs

有没有一种创建函数的方法,这样我就可以将javascript方法应用于函数中的React元素变量。

getTextBoxWidth(){
  var myTextBox = <text>Words here</text>;
  return myTextBox.textLength.baseVal.value;
}

1 个答案:

答案 0 :(得分:0)

有一种方法可以执行此操作,但不能完全按照您想要的方式进行。可以通过ref s:https://reactjs.org/docs/refs-and-the-dom.htmlEspecially this

但是有特殊条件。需要安装JSX.Element(在您的情况下为<text></text>)(意味着以一种或另一种方式呈现)。而且您将无法以同步方式获得结果。

class SomeParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.textRef = React.createRef();
    this.state = {
      textWidth: undefined
    };
  }

  componentDidMount() {
    this.setState({
      textWidth: this.textRef.current.textLength.baseVal.value
    });
  }

  render() {
    return <div>
      <div> Text width = {this.state.textWidth !== undefined ? this.state.textWidth : "unknown"}</div>

      <text ref={this.textRef}>Words here</text>
    </div>
  }
}