单击按钮时打印TextField-打印不正确

时间:2018-11-07 17:01:28

标签: javascript reactjs material-ui

我正在尝试在我的react应用程序中合并一个功能,用户将在其中输入搜索词,并且当按下按钮时它将进行搜索。 (文本输入和按钮正在使用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>
    );
  }
}

导出默认搜索

更新:固定错字

4 个答案:

答案 0 :(得分:0)

+ searchTem将对象强制转换为字符串,在您的情况下为[object Object]

只需将其更改为:

console.log("search: ", searchTerm)

您可以在此处了解更多信息:https://developer.mozilla.org/en-US/docs/Web/API/console#Outputting_text_to_the_console

答案 1 :(得分:0)

现在,您不调用handleClick,而只是通过控制台对其进行记录。这意味着您没有将state.searchTerm更改/设置为任何内容。是handleClick会更新状态。因此,该值将始终为null。您的句柄中也有错字单击:

您的参数说“ serchTerm”……应该说“ searchTerm”。您错过了一个;)

答案 2 :(得分:0)

类使用PascalCase,因为它们是组件,而不是简单的函数。 Buttons组件被严重终止,也许您可​​以只在用户单击按钮时简单地调用函数处理程序,然后在控制台上显示状态

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

  handleClick = (term) => {

    this.setState({ searchTerm: term });
    console.log(this.state.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={this.handleClick}
         varient ="contained"
         classname="goButton" >
         Enter Query Here!
        </Button>
     </div>
    );
  }
}

希望有帮助:)

答案 3 :(得分:0)

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

// 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}
                 />