react-pattern

Pattern of React Components

  • Stateless Components Can Be Written As A Function
1
2
3
4
5
6
7
8
9
10
11
12
export var statelessComp = (props)=> {
let message = props.message;
return (
<div>
<h1>stateless Components</h1>
<p>{message}</p>
</div>
);
}
statelessComp = {
message: React.PropTypes.string.isRequired
};
  • One of the most common programming patterns in React is to use stateful parent components to maintain their own state and pass it down to one or more stateless child components as props.

  • A React component should use state to store information that the component itself can change

  • A React component should never change its Props value.

  • Stateful Components pass event method as props to Stateless Components. Then, Stateless Components create a eventHandler method in order to change the state of Stateful Components.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//This is a stateless child component.
class babyYoda extends React.Component {
render() {
return <h2>I am {this.props.name}!</h2>;
}
}
//This is a stateful Parent element.
class Yoda extends React.Component {
constructor(props) {
super(props);
this.state = { name: 'Toyoda' };
}
//The child component is rendering information passed down from the Parent component.
render() {
return <babyYoda name={this.state.name} />;
}
}
  • Another programming patterns is Container Components From Presentational Components

    Use Container Components to do logical calculation.
    Use Presentational Components to render JSX elements.

使用默认props和设定props属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import PropTypes from 'prop-types';

class NavBar extends Component{
static defaultProps={
titile:'something on the top',
icon:'fab fa-gihub'
};
static propTypes = {
titile:PropTypes.string.isRequired,
icon:PropTypes.string.isRequired,
}
render(){
return (
<nav>
<h1><i className={this.props.icon}></i>{this.props.title}</h1>
</nav>
)
}
}

Functional compoents

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import PropTypes from 'prop-types';

const NavBar = (props)=>{
return (
<nav>
<h1><i className={props.icon}></i>{props.title}</h1>
</nav>
)
}
NavBar.defaultProps={
titile:'something on the top',
icon:'fab fa-gihub'
};
NavBar.propTypes = {
titile:PropTypes.string.isRequired,
icon:PropTypes.string.isRequired,
}

Save local environment variables

  • Create .env.local file in root directory
  • set key-value pair to create variables
  • then the variables can be accessed by process.env.${key}
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2020 Ruoyu Wang
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信