反应:在按钮上单击:转到以输入形式声明的URL

时间:2019-06-28 13:04:05

标签: reactjs

当我单击按钮时,我尝试转到输入字段中声明的URL。我对React完全陌生,因此不胜感激!

这是当前组件:

class MyComponent extends React.Component {
  render(){
    return (
        <form>
          <input type="text" name="code" placeholder="http://www.google.de" />
          <input type="button" value="Go" />
        </form>
    )
  }
}

2 个答案:

答案 0 :(得分:1)

以下是使用refs的解决方案:-

class App extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }
  submitHandler = () => {
    let value = this.inputRef.current.value;
    console.log(value);
    if (value !== "") window.location.href = value;
  };
  render() {
    return (
      <form onSubmit={() => this.submitHandler()}>
        <input
          ref={this.inputRef}
          type="text"
          name="code"
          placeholder="http://www.google.de"
        />
        <input type="submit" value="Go" />
      </form>
    );
  }
}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root' />

答案 1 :(得分:1)

使您的输入完全受控即可解决问题。代码注释中的说明

class MyComponent extends React.Component {
  state = {
    code: '' // initial value
  }
  
  // save code in state on change
  setCode = e => this.setState({code: e.target.value})
  
  // change href to be this.state.code value
  go = e => {
    e.preventDefault()
    
    window.location.href = this.state.code
  }
  
  render(){
    return (
        <form>
          {/* make input fully controlled */}
          <input type="text" name="code" value={this.state.code} onChange={this.setCode} placeholder="http://www.google.de" />
          {/* handle button click event*/}
          <input type="button" value={`Go to ${this.state.code}`} onClick={this.go}/>
        </form>
    )
  }
}

ReactDOM.render(<MyComponent/>, document.querySelector('#root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" />