class
import React
, { Component
} from 'react';
import './App.css';
import Person
from './Person/person';
import { render
} from '@testing-library/react';
class App extends Component{
state
={
persons
:[
{name
:'Max' , age
:28},
{name
:'manu' , age
:24},
{name
:'Snie' , age
:26}
]
};
switchNameHandler = ()=>{
this.setState({persons
:[
{name
:'Max1' , age
:281},
{name
:'manu1' , age
:241},
{name
:'Snie1' , age
:261}
]
})
};
render(){
return (
<div className
="App">
<h1
>Hi i am a React App
!</h1
>
<p
>It is working
!</p
>
<button onClick
={this.switchNameHandler
}>Switch Name
</button
>
<Person name
={this.state
.persons
[0].name
} age
={this.state
.persons
[0].age
}/>
<Person name
={this.state
.persons
[1].name
} age
={this.state
.persons
[1].age
}>My Hobbies
: Racing
</Person
>
<Person name
={this.state
.persons
[2].name
} age
={this.state
.persons
[2].age
}/>
</div
>
);};
}
export default App
;
在set中传入name
并将该函数传入< person >中;
switchNameHandler = (name
)=>{
this.setState({persons
:[
{name
:name
, age
:281},
{name
:'manu1' , age
:241},
{name
:'Snie1' , age
:261}
]
})
};
render(){
return (
<div className
="App">
<h1
>Hi i am a React App
!</h1
>
<p
>It is working
!</p
>
<button onClick
={this.switchNameHandler
.bind(this,'Blue')}>Switch Name
</button
>
<Person
name
={this.state
.persons
[0].name
}
age
={this.state
.persons
[0].age
}
click
={this.switchNameHandler
.bind(this,'BOB')}/>
<Person name
={this.state
.persons
[1].name
} age
={this.state
.persons
[1].age
}>My Hobbies
: Racing
</Person
>
<Person name
={this.state
.persons
[2].name
} age
={this.state
.persons
[2].age
}/>
</div
>
);};
}
在people.js中调用改click
import React
from 'react';
const person = (props
)=>{
return(
<div
>
<p
>I Am a person
!</p
>
<p onClick
= {props
.click
}>{props
.name
}</p
>
<p
>i'm
{props
.age
}</p
>
<p
>{props
.children
}</p
>
</div
>
)
};
export default person
;
bind传入参数比()=>传入速度快
<Person
name
={this.state
.persons
[1].name
}
age
={this.state
.persons
[1].age
}
click
={()=>this.switchNameHandler('hello')}
>My Hobbies
: Racing
</Person
>
转载请注明原文地址:https://ipadbbs.8miu.com/read-10285.html