markdown 04 - 使用道具

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 04 - 使用道具相关的知识,希望对你有一定的参考价值。

# Working with Props

- props is a special object that is passed to components by default
- props are accessed differently in stateful and stateless components
- in stateful, use {this.props.name}
- in stateless, use {props.name}


- a special prop, children allows us to access any element between the opening and closing tags of a component

## In Main Component


### Code Example
```
import React, {Component} from 'react';

class App extends Component {
  render() {
    return (
      <div>
        // passing attributes (i.e. props) to the person component
        <Person name="Brad" age="22" />
        // passing data between the opening and closing tags of a component i.e. children
        <Person name="Eleanor" age="21">My hobbies include make-up and animals</Person>
      </div>
    );
  }
}
export default App;
```

## In Secondary Component

- secondary component will output:
  - 1st person component: "Hi! Im Brad and Im 22 years old"
  - 2nd person component: "Hi! Im Eleanor and Im 21 years old" "My hobbies involve make-up and animals"
- if no props.children exists then no output will render for that paragraph

### Code Example
```
import React from 'react';

const person = (props) => {
  return (
    <p>Hi! Im {props.name} and Im {props.age} years old</p>
    <p>{props.children}</p>
  );
}
export default App;
```

以上是关于markdown 04 - 使用道具的主要内容,如果未能解决你的问题,请参考以下文章

markdown 40 - 验证道具

markdown 38 - 传递未知的道具

markdown 道具(子へのデータの渡し方)

使用道具传递 _setTitle 方法是不是可行?

如何在方法中使用 Vue 道具作为变量?

如何将道具传递给组件的故事?