m.Group as={Row} controlId="formHorizontalEmail">
<Form.Label column sm={2}>
<span className="item">Item</span>
</Form.Label>
<Col sm={5}>
<Form.Control type="text" placeholder="Todo Item" />
</Col>
<Col sm={5}>
<Button variant="primary" type="submit">Add</Button>
</Col>
</Form.Group>
</Form>
</div>
);
}
}
非受控组件
大多数情况下,建议使用受控组件。有一种称为非受控组件的方法可以通过使用Ref
来处理表单数据。在非受控组件中,Ref
用于直接从DOM
访问表单值,而不是事件处理程序。
我们使用Ref
构建了相同的表单,而不是使用React状态。 我们使用React.createRef()
定义Ref
并传递该输入表单并直接从handleSubmit
方法中的DOM
访问表单值。
import React from 'react';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
export class ToDoForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.input = React.createRef();
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
alert('A name was submitted: ' + this.input.current.value);
event.preventDefault();
}
render() {
return (
<div className="todoform">
<Form>
<Form.Group as={Row} controlId="formHorizontalEmail">
<Form.Label column sm={2}>
<span className="item">Item</span>
</Form.Label>
<Col sm={5}>
<Form.Control type="text" placeholder="Todo Item" ref={this.input}/>
</Col>
<Col sm={5}>
<Button variant="primary" onClick={this.handleSubmit} type="submit">Add</Button>
</Col>
</Form.Group>
</Form>
</div>
);
}
}
容器组件
容器组件是处理获取数据、订阅 redux 存储等的组件。它们包含展示组件和其他容器组件,但是里面从来没有html。
高阶组件
高阶组件是将组件作为参数并生成另一个组件的组件。 Redux connect
是高阶组件的示例。 这是一种用于生成可重用组件的强大技术。
Props 和 State
Props 是只读属性,传递给组件以呈现UI和状态,我们可以随时间更改组件的输出。
下面是一个类组件的示例,它在构造函数中定义了props
和state
,每当使用this.setState()
修改状态时,将再次调用 render( )
函数来更改UI中组件的输出。
import React from 'react';
import '../App.css';
export class Dashboard extends React.Component {
constructor(props){
super(props);
this.state = {
name: "some name"
}
}
render() {
// reading state
const name = this.state.name;
//reading props
const address = this.props.address;
return (
<div className="dashboard">
{name}
{address}
</div>
);
}
}
什么是PropTypes
随着时间的推移,应用程序会变得越来越大,因此类型检查非常重要。PropTypes
为组件提供类型检查,并为其他开发人员提供很好的文档。如果react项目不使用 Typescript,建议为组件添加 PropTypes
。
如果组件没有收到任何 props,我们还可以为每个组件定义要显示的默认 props。这里有一个例子。UserDisplay
有三个 prop:name
、address
和age
,我们正在为它们定义默认的props 和 prop类型。
import React from 'react';
import PropTypes from 'prop-types';
export const UserDisplay = ({name, address, age}) => {
UserDisplay.defaultProps = {
name: 'myname',
age: 100,
address: "0000 onestreet"
};
return (
<>
<div>
<div class="label">Name:</div>
<div>{name}</div>
</div>
<div>
<div class="label">Address:</div>
<div>{address}</div>
</div>
<div>
<div class="label">Age:</