我想通過使用來創建一個表單<input>,<button>如下所示:

當我按下“立即發送”按鈕時,我不確定如何將從文本輸入欄位中獲得的值傳遞給前端的幾個函式。如何在<form onSubmit={}>不使用表單的情況下制作一個,而只是一個輸入欄位和一個按鈕?
這是我迄今為止嘗試過的,但它不起作用,我不確定如何獲取輸入值并將其傳遞給這樣的函式this.articleOnSubmit(*user input*)。而且我合并的方式onChange={this.articleOnChange}是否正確?這是我的代碼:
const Input = ({ placeholder, name, type, value }) => (
<input
placeholder={placeholder}
type={type}
step="0.0001"
value={value}
name={value}
/>
);
class Publish extends Component {
constructor(props) {
super(props);
this.state = {
articleTitle: '',
};
}
articleOnChange = (event) => {
let title = event.target.value;
this.setState({ articleTitle: title.toLowerCase() });
}
articleOnSubmit = (event) => {
if (this.state.articleTitle) {
console.log(this.state.articleTitle);
this.hash(this.state.articleTitle)
.then(hex => {console.log(hex); return hex;})
.then(hex => this.addArticleHash(hex));
event.preventDefault();
}
return (
<Input placeholder="Article Name" name="article" type="text" onChange={this.articleOnChange} />
<div/>
{false
? (<Loader />)
: (
<button
type="submit"
onClick={this.articleOnSubmit(Input.name)}
>
Send now
</button>
)}
</div>
);
}
uj5u.com熱心網友回復:
要使其正常作業,您必須在此處解決 2 個問題:
- 由于
Input是一個組件,因此您必須將onChange傳遞給它的 props 放入它的 props 中,否則它將無法作業。
const Input = ({ placeholder, name, type, value, onChange }) => (
<input
onChange={onChange}
placeholder={placeholder}
type={type}
step="0.0001"
value={value}
name={value}
/>
);
- React
onClick應該是一個函式。不是電話。一個函式。你在這里所做的是onClick={this.articleOnSubmit(Input.name)}- 這是一個電話。
解決辦法是把它改成函式 () => this.articleOnSubmit(Input.name)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/411656.html
標籤:
上一篇:在反應打字稿中將檔案作為道具傳遞(型別'true'不可分配給型別'ChangeEventHandler<HTMLInputElement>)
下一篇:當狀態改變時反應切換主體類
