Javascript 使用prop回调将参数从子级传递到父级
在这里,您可以很容易地看到从父对象上的子对象运行函数的方法Javascript 使用prop回调将参数从子级传递到父级,javascript,reactjs,Javascript,Reactjs,在这里,您可以很容易地看到从父对象上的子对象运行函数的方法 但是,如何从子组件传递带有函数的参数?如果需要父组件的状态,则必须在传递之前将其绑定到函数 class Parent extends React.Component { callMeMaybe(param) { console.log(param) } render(){ return ( <TheChild callMeMaybe={this.callMeMaybe.bind(this)
但是,如何从子组件传递带有函数的参数?如果需要父组件的状态,则必须在传递之前将其绑定到函数
class Parent extends React.Component {
callMeMaybe(param) {
console.log(param)
}
render(){
return (
<TheChild callMeMaybe={this.callMeMaybe.bind(this)} />
)
}
}
class TheChild extends React.Component {
render(){
return (
<div>
<button onClick={ event => {
this.props.callMeMaybe("message from child") }
}>Send a Message to Parent </button>
</div>
)
}
}
类父级扩展React.Component{
callMeMaybe(参数){
console.log(参数)
}
render(){
返回(
)
}
}
类child扩展React.Component{
render(){
返回(
{
this.props.callMeMaybe(“来自孩子的消息”)}
}>向家长发送消息
)
}
}
这是一个供你玩的游戏。单击按钮后检查控制台。如果需要来自父组件的状态,则必须在传递它之前将其绑定到函数
class Parent extends React.Component {
callMeMaybe(param) {
console.log(param)
}
render(){
return (
<TheChild callMeMaybe={this.callMeMaybe.bind(this)} />
)
}
}
class TheChild extends React.Component {
render(){
return (
<div>
<button onClick={ event => {
this.props.callMeMaybe("message from child") }
}>Send a Message to Parent </button>
</div>
)
}
}
类父级扩展React.Component{
callMeMaybe(参数){
console.log(参数)
}
render(){
返回(
)
}
}
类child扩展React.Component{
render(){
返回(
{
this.props.callMeMaybe(“来自孩子的消息”)}
}>向家长发送消息
)
}
}
这是一个供你玩的游戏。单击按钮后检查控制台。使用参数从子级调用绑定函数
const IncrementOne=props=>(
道具增量(1)}>
增量1
);
const IncrementTwo=props=>(
道具增量(2)}>
增量2
);
常量增量x=props=>(
props.increment(props.x)}>
增量{props.x}
);
类父类扩展了React.Component{
建造师(道具){
超级(道具);
this.state={counter:0};
this.increment=this.increment.bind(this);
}
增量(金额){
让计数器=this.state.counter+金额;
this.setState({counter});
}
render(){
返回(
{this.state.counter}
);
}
}
ReactDOM.render(,document.getElementById('app'))代码>
使用参数从子级调用绑定函数
const IncrementOne=props=>(
道具增量(1)}>
增量1
);
const IncrementTwo=props=>(
道具增量(2)}>
增量2
);
常量增量x=props=>(
props.increment(props.x)}>
增量{props.x}
);
类父类扩展了React.Component{
建造师(道具){
超级(道具);
this.state={counter:0};
this.increment=this.increment.bind(this);
}
增量(金额){
让计数器=this.state.counter+金额;
this.setState({counter});
}
render(){
返回(
{this.state.counter}
);
}
}
ReactDOM.render(,document.getElementById('app'))代码>
向任何“其他”函数传递参数的相同方式:fn(参数)
。向任何“其他”函数传递参数的相同方式的可能重复:fn(参数)
。的可能重复