我正在执行简单的React js任务,当用户在按钮上的文本字段中输入值时,单击“我想查看要设置的值”。
我正在粘贴App.js代码,请忽略person.js,我未将其用于任务。
不确定当我单击按钮时是否还要设置值,我确定我在这里遗漏了一些东西。
App.js
import React, { Component } from 'react';
class App extends Component {
constructor(props)
{
super(props);
this.state =
{
};
this.setValue = this.setValue.bind(this);
}
setValue = (event) =>
{
this.setState(
{
a:event.target.value
}
)
}
render() {
return (
<div className="App">
<button type="button" onClick={this.setValue}>Set value</button>
<input type="text" value={this.changed}></input>
</div>
);
}
}
export default App;
答案 0 :(得分:0)
通常,输入应具有value属性(用于设置值,通常是来自状态),该onHandler事件处理程序会在每次更改输入时更新状态。
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Person from './Person';
class App extends Component {
constructor(props)
{
super(props);
this.state = {
objects: [
{coin: "bitcoin",price:6500},
{coin: "saicoin",price:1},
{coin: "vechain",price:4},
{coin: "nano",price:3}
]
};
this.setValue = this.setValue.bind(this);
}
setValue = (event) => {
this.setState({
a:event.target.value
});
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
<button type="button" onClick={this.setValue}>Set value</button>
<input type="text" value={this.state.a} onChange={this.setValue}></input>
<h1>{this.state.objects[0].coin} {this.state.objects[0].price}</h1>
<h1>{this.state.objects[1].coin} {this.state.objects[1].price}</h1>
<h1>{this.state.objects[2].coin} {this.state.objects[2].price}</h1>
<h1>{this.state.objects[3].coin} {this.state.objects[3].price}</h1>
<h1>{this.state.a}</h1>
</p>
</div>
);
}
}
export default App;
答案 1 :(得分:0)
onChange事件处理程序应该在输入元素中以获取键入的值并将其设置为一个状态,并将该状态作为值传递给输入元素。
您应该执行以下操作。
constructor(props){
super(props);
this.state={
value: “”
}
}
setValue(event){
this.setState({
value: event.target.value
});
}
<input type="text" onChange={this.setValue} value={this.state.value}></input>
答案 2 :(得分:0)
只需使用受控输入即可,将其值存储为更改后的状态。比使用点击状态值更高-通常通过onClick
函数prop:
class App extends React.Component {
state = {
value: ''
}
handleChange = ({ target: { value }}) => {
this.setState({ value });
}
handleClick = () => {
const { value } = this.state;
const { onClick } = this.props;
onClick(value);
}
render() {
const { value } = this.state;
return (
<div>
<p>state: {`{ value: '${value}' }`}</p>
<input value={value} onChange={this.handleChange} />
<button onClick={this.handleClick}>Set value</button>
</div>
);
}
}
const handleChildClick = value => alert(`"${value}" has been set in App`);
ReactDOM.render(<App onClick={handleChildClick} />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>