我使用React状态组件已经有一段时间了,特别是在表单和其他类型的用户交互上。我使用的典型输入组件如下:
import React, { Component } from "react";
import PropTypes from "prop-types";
import styled, { ThemeProvider } from "styled-components";
import { theme } from "../theme";
class Input extends Component {
static propTypes = {
onChange: PropTypes.func,
label: PropTypes.string,
errorMessage: PropTypes.string,
value: PropTypes.any
};
state = {
errorMessage: null,
value: null
};
componentWillMount = () => {
this.setState({
errorMessage: this.props.errorMessage,
value: this.props.value
});
};
componentWillReceiveProps = nextProps => {
this.setState({
errorMessage: nextProps.errorMessage,
value: nextProps.value
});
};
handleChange = event => {
alert("handleChange!")
this.setState({
errorMessage: null,
value: event.taget.value
});
if (this.props.onChange) this.props.onChange(event.target.value);
};
render = () => {
let { label } = this.props;
let { errorMessage, value } = this.state;
alert("Render")
let err = null;
if (errorMessage) err = <label>{errorMessage}</label>;
return (
<ThemeProvider theme={theme}>
<label>{label}</label>
<input
onChange={this.handleChange}
type={"text"}
value={value}
/>
{err}
</ThemeProvider>
);
};
}
export default Input;
我现在将这些组件移至Storybook。以下是上述Input
组件的第一篇文章:
import React from "react";
import { storiesOf } from "@storybook/react";
import Input from "./Input";
const noOp = event => {
event.preventDefault();
};
storiesOf("Forms/Input", module).add("errorMessage", () => (
<Input
label={"Insert Data"}
onChange={noOp}
errorMessage={"Error Message Here!"}
/>
));
我注意到的是,故事书不会在组件状态更改时调用渲染(alert(Render)
仅被调用一次,而在onChange
上更改状态时则不会被调用,即使被调用
感觉故事书不像我以前那样支持状态更改...
如何在故事书中正确使用有状态组件(例如React Forms)?
在我的简单示例中需要进行哪些更改才能使其在故事书中起作用?