[英]ReactJS: How to change Text value on button click
我正在我的應用程序中創建一個表單,需要在其中添加數量字段。 我從通知中添加了<Text>
組件以添加數量字段,並使用按鈕添加了增減功能。
但是我不能在單擊按鈕時設置“文本”組件值。 看來我只能為<Text>
組件設置initialValue
。
import React, { Component } from 'react';
import { arrayOf, number, shape, string } from 'prop-types';
import classify from 'src/classify';
import defaultClasses from './quantity.css';
import { Text } from 'informed';
class Quantity extends Component {
static propTypes = {
classes: shape({
root: string,
increment_button: string,
decrement_button: string,
quantity_input: string
}),
items: arrayOf(
shape({
value: number
})
)
};
state = {
quantity: 1,
show: true,
max: 9999,
min: 1
};
incrementQty = () => {
this.setState(prevState => {
if(prevState.quantity < this.state.max) {
return {
quantity: parseInt(prevState.quantity) + 1
}
} else {
return null;
}
});
/*this.setState({ quantity: parseInt(this.state.quantity) + 1 });*/
};
decrementQty = () => {
this.setState(prevState => {
if(prevState.quantity > this.state.min) {
return {
quantity: parseInt(prevState.quantity) - 1
}
} else {
return null;
}
});
/*this.setState({ quantity: parseInt(this.state.quantity) - 1 });*/
};
setQuantity = quantity => this.setState({ quantity });
handleChange = (event) => {
this.setState({quantity: event.target.value});
};
render() {
const { classes, ...restProps } = this.props;
console.log(this.state.quantity);
return (
<div className={classes.root}>
<span onClick={this.decrementQty} className={classes.decrement_button}>-</span>
<Text
initialValue = {`${this.state.min}`}
className={classes.quantity_input}
field="quantity"
onChange={this.handleChange}
value={this.state.quantity}
label=""
/>
<span onClick={this.incrementQty} className={classes.increment_button}>+</span>
</div>
);
}
}
export default classify(defaultClasses)(Quantity);
我嘗試value
道具,但無法正常工作。 如果我使用不受控制的html <input>
字段,則按鈕和數量增量遞減有效,但是我不想在表單中使用<input>
元素。
也許你的代碼應該是
onChange={quantity => this.handleChange(quantity)}
和你的代碼來處理狀態更新
onChange = (e) => {
this.setState({
[e.target.name]: e.target.value
});
}
您是對的,知情的Text
沒有prop value
,我發現了一個技巧,只需單擊一下按鈕即可設置Text
的值。
您可以使用React.createRef
來創建引用,然后通過該引用設置值。
class App extends React.Component {
constructor(props) {
super(props);
this.ref = React.createRef();
}
state = {
min: 10
};
changeQt = () => {
this.ref.current.value = 20;
};
render() {
return (
<div className="App">
<Text
initialValue={`${this.state.min}`}
field="quantity"
onChange={this.handleChange}
label=""
ref={this.ref}
/>
<button onClick={this.changeQt}>Click</button>
</div>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.