首页 > 解决方案 > 在提交时获取 material-ui TextField 值

问题描述

我想获取 TextField 输入的值并有条件地呈现消息。我试过这个,它可以工作,但这个是动态运行的,因为我使用了onChange. 我想达到同样的效果,但是使用onSubmiton<Button>有没有办法做到这一点?

import React from 'react';
import { Component } from 'react';
import Button from '@mui/material/Button';
import { TextField } from '@mui/material';
class App extends Component 
{ 
    state = { 
        myValue: null, 
    } 
 
    handleChange = (e) => this.setState({ 
        myValue: e.target.value 
    }) 
     
    render() { 
        return ( 
            <div>
            <TextField 
                value={this.state.myValue} 
                onSubmit={this.handleChange}
            />
            <button  >Get Weather</button>
            {this.state.myValue ? <p>value inputed </p>: <p>no input</p>}
            
            </div>

        ) 
    } 
} 


export default App;

标签: javascriptreactjsmaterial-ui

解决方案


使用Refs是您所需要的。您可以通过单击按钮获取输入的当前值,然后才更改状态。

演示

import React, { createRef } from "react";
import { Component } from "react";
import { TextField } from "@mui/material";
class App extends Component {
  constructor(props) {
    super(props);
    this.textInput = createRef();
    this.state = {
      myValue: ""
    };
  }
  showRefContent = () => {
    this.setState({
      myValue: this.textInput.current.value
    });
  };

  handleChange = (e) =>
    this.setState({
      myValue: e.target.value
    });

  render() {
    return (
      <div>
        <TextField inputRef={this.textInput} />
        <button onClick={this.showRefContent}>Get Weather</button>
        <p>
          {this.state.myValue.length > 0
            ? `text:${this.state.myValue}`
            : "no text"}
        </p>
      </div>
    );
  }
}

export default App;


推荐阅读