[英]How do I use a function to pass parameter to the function received as props in react?
import React, {Component} from 'react';
export default class InputBlock extends Component{
handleChange = (e, props) =>{ //Checked passing props didn't worked.
const inputVal = this.msgInput.value;
props.onMessageSent(inputVal);
e.preventDefault();
}
render(){
return (
<div>
<form onSubmit={this.handleSubmit} >
<input type="text" className="msgInput" ref = {input => this.msgInput = input}/>
<input type="submit" value = "submit" className="sendButton" />
</form>
</div>
)
}
}
在這里,我從父組件接收函數onMessageSent作為道具。 我想將輸入值傳遞給函數,以便可以將該值設置為state並將其作為道具傳遞給其他組件。 這是我的父組件:
import React, {Component} from 'react';
import Messages from './Messages';
import InputBlock from './InputBlock';
export default class MainInterface extends Component {
constructor(props){
super(props);
this.state = {
sent: [],
received: []
}
}
onMessageSent = (val) =>{
this.setState(prevState => ({
sent: [...prevState.sent, val]
}))
}
render(){
return (
<div>
<Messages sent={this.state.sent} received={this.state.received}/>
<InputBlock onChange = {this.onMessageSent} />
</div>
)
}
}
**注意:**有一種類型,應該是onMessageSent而不是onMessagesent。 很抱歉浪費您的時間。
您的組件被定義為ES6類,在這種情況下,您可以將組件的props稱為this.props
而無需將它們作為參數傳遞給類方法。 因此,您的方法應如下所示:
handleChange(e) {
const inputVal = this.msgInput.value;
this.props.onChange(inputVal);
e.preventDefault();
}
import React, {Component} from 'react';
export default class InputBlock extends Component{
handleChange = (e) =>{ //Checked passing props didn't worked.
const inputVal = this.msgInput.value;
this.props.onMessageSent(inputVal);
e.preventDefault();
}
render(){
return (
<div>
<form onSubmit={this.handleSubmit} >
<input type="text" className="msgInput" ref = {input => this.msgInput = input}/>
<input type="submit" value = "submit" className="sendButton" />
</form>
</div>
)
}
import React, {Component} from 'react';
import Messages from './Messages';
import InputBlock from './InputBlock';
export default class MainInterface extends Component {
constructor(props){
super(props);
this.state = {
sent: [],
received: []
}
this.onMessageSent= this.onMessageSent.bind(this)
}
onMessagesent = (val) =>{
this.setState(prevState => ({
sent: [...prevState.sent, val]
}))
}
render(){
return (
<div>
<Messages sent={this.state.sent} received={this.state.received}/>
<InputBlock onChange = {this.onMessageSent)} />
</div>
)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.