我正在编写一个反应组件,它读取用户的名字和第二个名称,然后为它们生成随机用户名。
class App extends Component {
render() {
return (
<div className="App">
First name:<br/>
<input type="text"></input><br/>
Last name:<br/>
<input type="text"></input><br/>
<button type="button">make a username</button>
<p>{generateUN('fname','lname')}</p>
</div>
);
}
}
触发按钮后,如何将输入字段中的值传递给函数?
答案 0 :(得分:4)
您可以使用州来创建用户名,这是一个小例子
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
fn : '',
ln : ''
}
}
// makeUsername creates
// the username based on the fn and ln
// provided in the inputs
makeUsername () {
const {fn, ln} = this.state;
// if either fn or ln is not provided, do nothing
if (!fn || !ln) return;
this.setState({
username : `${fn.trim()}@${ln.trim()}`
});
}
// createChangeHandleris a curried function to specify
// which piece of state will be modifed
createChangeHandler (stateKeyToUpdate) {
return (e) => {
this.setState({
[stateKeyToUpdate] : e.target.value
});
}
}
render () {
// conditional render
// if the username exists
// then render the div
/*{
username &&
<div>Your username is {username}</div>
}*/
const {fn, ln, username} = this.state;
return (
<div>
<input
value={fn}
onChange={this.createChangeHandler('fn')}
/>
<input
value={ln}
onChange={this.createChangeHandler('ln')}
/>
<button onClick={this.makeUsername.bind(this)}>
create username
</button>
{
username &&
<div>Your username is {username}</div>
}
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('#root'))
和demo
答案 1 :(得分:-1)
您可以使用内联onClick或eventlistener
First name:<br/>
<input type="text" id='btn1'></input><br/>
Last name:<br/>
<input type="text" id='btn2'></input><br/>
<button id='mybutton' onClick="myRandomFunction(getElementById(btn1).value,getElementById(btn2).value)" >make a username</button>
或者
<script>
getElementById('mybutton').addEventListener("click", myRandomFunction(getElementById(btn1).value,getElementById(btn2).value);
</script>