[英]I have buttons and a textbook in my React App, How do I make the click of the button trigger text input?
我有代表邏輯運算符的按鈕。 為了這個例子,假設我有一個按鈕,上面寫着 +當我點擊 + 按鈕時,我想在文本框內看到一個 + 作為輸入!
我提供了按鈕組件和文本框組件的代碼。 我總共有 7 個按鈕組件。
我意識到必須是 onClick (我那里的代碼不正確,只是一個占位符)
按鈕:
import React, { Component } from "react";
//logic operator buttons
class Logic extends Component {
state = {};
render() {
return (
<div
style={{
position: "absolute",
left: "10%",
top: "20%",
transform: "translate(-50%, -50%)",
}}
>
<button
onClick={this.handleIncrement}
className={"btn btn-primary btn-sm m-2 p-1"}
>
¬
</button>
</div>
);
}
}
export default Logic;
文本框:
import React, { Component } from "react";
class Textbox extends Component {
state = {};
render() {
return (
<div
style={{
position: "absolute",
left: "50%",
top: "17%",
transform: "translate(-50%, -50%)",
}}
className="form-group"
>
<label for="exampleLogicSymbol">Logic Operator</label>
<input
type="text"
className="form-control"
id="exampleInputLogic"
aria-describedby="logicHelp"
placeholder="enter formula"
></input>
</div>
);
}
}
export default Textbox;
這是一個簡化版本: https://codesandbox.io/s/autumn-glitter-y4fwt?file=/src/App.js
import React from "react";
import "./styles.css";
class App extends React.Component {
state = {
value: ""
};
handleChange = e => {
this.setState({ value: e.target.value });
};
plusOnClick = () => {
this.setState(state => ({
value: state.value + "+"
}));
};
render() {
return (
<div className="App">
<input
type="text"
onChange={this.handleChange}
value={this.state.value}
/>
<button onClick={this.plusOnClick}>+</button>
</div>
);
}
}
export default App;
本質上,您附加了一個 onClick function 來更新輸入的 state 值。
下面是代碼片段:
import React, { Component } from "react";
class Logic extends Component {
constructor(){
this.state={
value:""
}
handleIncrement(value)
{
this.setState({
value:value
});
}
render(){
var Value="¬";
return(
<div>
The value is: {this.state.value}
<button>
onClick={()=>{this.handleIncrement(Value)}}
className={"btn btn-primary btn-sm m-2 p-1"}>
{Value}
</button>
</div>);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.