ReactJS:我怎样才能更加模块化地使用道具类型&物体的形状? [英] ReactJS: How can I have a more modular use of prop types & shapes for objects?
问题描述
我喜欢为每个类明确指定所有道具类型。
I like to explicitly specify all my prop types for every class.
React.createClass({
propTypes: {
optionalArray: React.PropTypes.array,
optionalBool: React.PropTypes.bool,
...
这是通过阅读可重复使用的组件来实现的: https://facebook.github.io/react/docs/reusable-components.html
This is from reading reusable components: https://facebook.github.io/react/docs/reusable-components.html
但是,如果我有一个非常常见的对象,那该怎么办?在许多类中使用?例如:
However, what if I have a very common object that I use in many classes? For example:
var MemoryForm = React.createClass({
propTypes: {
memory: React.PropTypes.shape({
memoryID: React.PropTypes.number,
content: React.PropTypes.string,
date: React.PropTypes.object,
dateStr: React.PropTypes.string,
note: React.PropTypes.string
}).isRequired,
...
var MemoriesArea = React.createClass({
propTypes: {
// The initial memory to fill the memory form with.
formMemory: React.PropTypes.shape({ // <== shape used again
memoryID: React.PropTypes.number,
content: React.PropTypes.string,
date: React.PropTypes.object,
dateStr: React.PropTypes.string,
note: React.PropTypes.string
}).isRequired,
// ...
var Playground = React.createClass({
getInitialState: function() {
var initVars = {
// The initial memory to fill the memory form with.
formMemory: { // <== shape is used again.
memoryID: 0,
content: "",
date: null,
dateStr: "",
note: ""
}
};
return initVars;
}
//...
这里,我在各种类的道具类型中经常使用'记忆'形状,以及在一些初始化中。如何使这更干燥 - 即更少的代码重复,所以改为这个对象形状将来会更容易维护吗?
Here, I use the 'memory' shape very frequently in the prop types for various classes, as well as in some initializations. How can make this more DRY - i.e., less code duplication, so a change to this object shape will be more maintainable in the future?
推荐答案
我遇到了同样的问题,只是将值移到了单独的ES6中模块。在您的示例中:
I had the same problem and just moved the values to a separate ES6 module. In your example:
// File lib/PropTypeValues.js
import { PropTypes } from 'react';
export let MemoryPropTypes = PropTypes.shape({
memoryID: PropTypes.number,
content: PropTypes.string,
date: PropTypes.object,
dateStr: PropTypes.string,
note: PropTypes.string
}).isRequired
然后在您的客户端代码中:
Then in your client code:
// MemoryForm.jsx
import { MemoryPropTypes } from './lib/PropTypeValues'
import React from 'react';
class MemoryForm extends React.Component {
static propTypes: {
memory: MemoryPropTypes,
// ...
};
}
希望这有帮助。
这篇关于ReactJS:我怎样才能更加模块化地使用道具类型&物体的形状?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!