如何使用表单中的按钮使表单组件提交?

时间:2019-06-16 15:04:02

标签: reactjs material-ui

我有以下代码,其中文本输入框接受网址,如果有效,则应创建显示区域并提供该网址的漂亮预览。

但是我不确定如何将button的提交与form的提交关联起来。

import React, {useState} from 'react';
import './App.css';
import Microlink from '@microlink/react';
import { String } from 'core-js';
import Card from '@material-ui/core/Card';
import TextField from '@material-ui/core/TextField';
import Button from "@material-ui/core/Button";

function validURL(str) {
  var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
    '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
  return !!pattern.test(str);
}

function App (){
  const [myurl, setMyurl] = useState("")
  const [display, setDisplay] = useState(true)

  const handleChange = (event) => {
    const url = event.target.value    
    var str = validURL(url)
    console.log(str)
    str ? setMyurl(String(url)) : setDisplay(false)
  }

  return (    
    <form>
      <TextField
        id="outlined-name"
        label="Name"        
        margin="normal"
        variant="outlined"
        onSubmit={event => handleChange(event)}        
      />
      <Button
        type="submit"
        variant="contained"                          
      >
       Submit
      </Button>

      {display ? 
      <Card>
      <Microlink url={myurl}/>;        
    </Card> : null}


    </form>

  )
}

export default App;

1 个答案:

答案 0 :(得分:2)

您需要像这样将onSubmit放在form标记内。还需要具有受控形式。意思是,您需要一个onChange,我为您编写了。

 return (    
    <form onSubmit={event => handleChange(event)} >
      <TextField
        id="outlined-name"
        label="Name"        
        margin="normal"
        variant="outlined"
        value={myurl}
        onChange={e => setMyUrl(e.target.value)}

      />
      <Button
        type="submit"
        variant="contained"                          
      >
       Submit
      </Button>

      {display ? 
      <Card>
      <Microlink url={myurl}/>;        
    </Card> : null}


    </form>

  )
}

export default App;