3-1如何定义一个组件,以及在父组件中的使用

  1. //如果要使用组件,在src下面新建一个components/Title.js
  2. import React from 'react'
  3. class Title extends React.Component{
  4. constructor(props){
  5. super(props)
  6. }
  7. render(){
  8. return(
  9. <h1>{this.props.msg}</h1>
  10. )
  11. }
  12. }
  13. export default Title;
  14. export default Header;
  15. //在App.js中导入组件
  16. import Title from './components/Title'
  17. //在App.js中使用
  18. <Title/>

3-2父组件给子组件传参

  1. //父组件
  2. import React from 'react';
  3. import Title from './components/Title'
  4. class App extends React.Component{
  5. constructor(props){
  6. super(props);
  7. this.state={
  8. msg:"hello world"
  9. }
  10. }
  11. render(){
  12. return(
  13. <div>
  14. <Title
  15. //1.子组件的属性接收父组件传递过来的方法
  16. deleteItem={this.handleDelete.bind(this)}
  17. msg={this.state.msg}></Title>
  18. </div>
  19. )
  20. }
  21. handleDelete(id){
  22. console.log(id)
  23. }
  24. }
  25. export default App;
  1. //子组件
  2. import React from 'react'
  3. class Title extends React.Component{
  4. constructor(props){
  5. super(props)
  6. }
  7. render(){
  8. return(
  9. <h1 onClick={this.handleClick.bind(this,'1123')}>{this.props.msg}</h1>
  10. )
  11. }
  12. handleClick=(id)=>{
  13. //2.子组件调用方法,向父组件传参
  14. this.props.deleteItem(id)
  15. }
  16. }
  17. export default Title;

3-3父组件中发送请求之后向子组件传值,在子组件中遍历渲染数据

  1. //父组件
  2. import React from 'react';
  3. import Delete from './components/Delete'
  4. class App extends React.Component{
  5. constructor(props){
  6. super(props);
  7. this.state={
  8. msg:"hello world",
  9. playlists:[]
  10. }
  11. }
  12. render() {
  13. return(
  14. <div> //父组件使用属性向子组件传值
  15. <Delete content={this.state.playlists}></Delete> //自定义属性content传参
  16. </div>
  17. )
  18. }
  19. //发送请求 挂载到原型上
  20. componentDidMount(){
  21. var url='https://music.aityp.com/top/playlist?cat=华语'
  22. this.$http.get(url).then(res=>{
  23. var playlists=res.data.playlists;
  24. this.setState({
  25. playlists
  26. })
  27. })
  28. }
  29. }
  30. export default App;
  1. //子组件通过this.props使用数据
  2. import React from 'react'
  3. class Delete extends React.Component{
  4. constructor(props){
  5. super(props)
  6. }
  7. render() {
  8. return(
  9. <div>
  10. {this.props.content.map(item=>{ //通过this.props接收传过来的参数
  11. return(<div key={item.id}>
  12. <p>{item.name}</p>
  13. </div>)
  14. })}
  15. </div>
  16. )
  17. }
  18. }
  19. export default Delete