【问题标题】:Pass a variable to another function through onClick通过 onClick 将变量传递给另一个函数
【发布时间】:2022-06-22 16:49:38
【问题描述】:

我有这个功能:

 function ValueForm(){
  const [name, setName] = useState("");
  return (
      <div>
        <label>
          Value: 
        </label>
        <input 
        type="text" 
        name={name}
        onChange={(e) => setName(e.target.value)}
        />
        <div className="col-md-4">
          <button type="button"
          onClick={()=> Search(name)}
          >Search
          </button>
          
        </div>
        
        

      </div>

    );

}


我通过onClick={()=&gt;Search(name)} 的目标是调用我的函数Search 并将输入值“name”从函数ValueForm 中的表单作为变量传递给它。看来这不是正确的方法,我没有找到任何答案。我该怎么办?

这是我的搜索功能

function Search(name){

    const items = [];
    let {value} =name;
    const url=`https://api.github.com/users/${value}`;

    fetch(url,{
        method:'GET'
    }).then(response => response.json())
      .then(function(data){
          console.log(data, value)
      .then((json)=> {this.setState({
        items: json,
        });

      })

            
        })
      
      return(
        <GithubUser
          name={this.items.name}
          location={this.items.location}
          avatar={this.items.avatar}
        />
      )  
}

【问题讨论】:

  • “似乎这不是正确的方法” - 是什么让你这么认为? Search 是什么?
  • 检查控制台中的错误。

标签: javascript reactjs


【解决方案1】:
 <input 
        type="text" 
        name={name}
        onChange={(e) => setName(e.target.value)}
        />

将您的 name 属性更改为 value。在您当前的代码中,没有值字段。所以你的 event.target.value 一直是未定义的

【讨论】:

    猜你喜欢
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    相关资源
    最近更新 更多