按钮点击调用具有React State的函数



我是新手,

我正在尝试将按钮onclick上的值从一个组件传递到另一个组件。

这是我的以下代码:

联系人组件:

import React,{useState} from 'react';
import Section from '../../../HOC/Section';
import apicall from '../../UI/JS/allapicall.js';
const Contact = () => {
const [name, setName] = useState(0);
console.log("name");
return (
<Section id='contact'>
<div className='container pt-2 pb-5'>
<div className='section-header pt-5 pb-5 text-center'>
<h3 className='section-title'>
<span>Get in touch with </span>Us
</h3>
<h6 className='section-subtitle mr-auto ml-auto'>
We are here with you 
</h6>
</div>
<div className='section-content'>
<div className='row'>
<div className='col-md-9 col-lg-7 mr-auto ml-auto'>
{/* <form> */}
<div className='form-group'>
<input
type='text'
className='form-control rounded-0'
aria-describedby='emailHelp'
placeholder='Enter Name...'
onChange={e=>setName(e.target.value)}
/>
</div>
<div className='form-group'>
<input
type='email'
className='form-control rounded-0'
aria-describedby='emailHelp'
placeholder='Enter email...'

/>
</div>
<div className='form-group'>
<textarea
className='form-control rounded-0'
rows='5'
placeholder='Enter Message...'
/>
</div>
<div className='form-group text-center'>
<button className='btn btn-block btn-primary rounded-0 mr-auto ml-auto' onClick={apicall({name})}>
Send
</button>
</div>
{/* </form> */}
</div>
</div>
</div>
</div>
</Section>
);
};
export default Contact;

apicall.js:

export default function messagesubmit(test)
{
console.log(test);
const axios = require('axios');
// Optionally the request above could also be done as
axios.get('https://www.zohoapis.com/crm/v2/functions/ticket_create/actions/execute?auth_type=apikey', {
params: {
zapikey: "1003.9145fb5d691b5f95a194c17e56300ed3.1cc7246813d8d6842c47f543a4f50b8f"
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
}

目前:对于每个状态的更改(当我更改文本字段的"值"时),onClick按钮函数调用react,console.log(test);每次更改名称都要打印,我不知道我哪里做错了,我只需要在onclick事件上触发它。

这是我想要的:

  1. 对于每个字段值,我需要将值存储在状态中
  2. 点击按钮我需要将状态中存储的值传递给参数内的消息提交函数

提前感谢

<button className='btn btn-block btn-primary rounded-0 mr-auto ml-auto' onClick={apicall({name})}>
Send
</button>

将其更改为:

<button className='btn btn-block btn-primary rounded-0 mr-auto ml-auto' onClick={() => apicall({name})}>
Send
</button>

您的按钮的onClick需要是() => apicall({name}),而不仅仅是apicall({name})。当您将onClick设置为apicall({name})时,会立即调用apicall({name}),并将onClick设置为该调用的结果。

最新更新