首页 > 解决方案 > 单击按钮时打印 TextField - 打印不正确

问题描述

我正在尝试在我的反应应用程序中合并一个功能,用户将在其中输入搜索词,当按下按钮时,它会搜索它。(文本输入和按钮正在使用 material-ui 组件)现在我只想让它将术语打印到控制台日志以检查它是否正常。运行以下代码时,输​​出为:“[object Object]。有谁知道这是为什么?

 import React from 'react';
 import TextField from '@material-ui/core/TextField';
 import Button from '@material-ui/core/Button';

class searchText extends React.Component {
  state = {
    searchTerm: null,
  }

  handleClick = (searchTerm) => {
    this.setState({ searchTerm });
  }

  render() {
    const { searchTerm } = this.state;

    return (
      <div className ="Search">
        <TextField 
          id = "outlined-search"
          label="Enter Query"
          type = "search"
          className ="Search"
          variant="filled"
          value = {searchTerm}
         />

        <Button
         onClick={() =>{console.log("search: " +{searchTerm}); }}
         varient ="contained"
         classname="goButton" >
         Enter Query Here!
        <Button/>
     </div>
    );
  }
}

导出默认搜索

更新:修正错别字

标签: javascriptreactjsmaterial-ui

解决方案


您没有任何功能来获取输入值并将该值设置为状态。尝试这个。

// function for TextField Value Change
    getvalue=(event)=>{
        this.setState({
          searchTerm:event.target.value
        })
    }
// function for button click
    handleClick = () => {
        console.log(this.state.searchTerm)
    }

                <TextField 
                  id = "outlined-search"
                  label="Enter Query"
                  type = "search"
                  className ="Search"
                  variant="filled"
                  value = {this.state.searchTerm}
                  onChange={this.getvalue}
                 />

推荐阅读