[英]How to split up single component code into multiple files in react
Hey so my component is getting really large and I want to store some of the code in another file without making a new component.嘿,所以我的组件变得非常大,我想将一些代码存储在另一个文件中而不创建新组件。 Basically I just want my code replicated word for word.基本上我只希望我的代码逐字复制。 For example例如
<fieldset className="container-form__field" name={fieldName} key={fieldName}>
<label>Select Model Type</label>
<select
name={`${fieldName}.modelType`}
required
ref={register({ required: true })}
>
{allModelTypes.map((modelType, index) => (
<option key={index}>{modelType}</option>
))}
</select>
{errors.modelType && <span>This field is required</span>}
<label>
Last Name {index}:
<input type="text" name={`${fieldName}.lastName`} ref={register} />
</label>
<button type="button" onClick={removeModel(index)}>
Remove
</button>
</fieldset>
As you can see here this part of my component is very dependant on the state inside this component so I can't just split it up into another component as I'll lose my state.正如您在此处看到的,我的组件的这一部分非常依赖于该组件内的 state,因此我不能将其拆分为另一个组件,因为我会丢失 state。 Ideally, I want to store this code in a separate file and just use that file to insert the code in my main component.理想情况下,我想将此代码存储在一个单独的文件中,然后使用该文件将代码插入我的主要组件中。
One of the main design principles in React is Composition . React 的主要设计原则之一是组合。
You can't just "replicate" code to another file, you need to make a component from it.您不能只是将代码“复制”到另一个文件,您需要从中制作一个组件。
Code like this:像这样的代码:
<select
name={`${fieldName}.modelType`}
required
ref={register({ required: true })}
>
{allModelTypes.map((modelType, index) => (
<option key={index}>{modelType}</option>
))}
</select>
May become:可能会变成:
// SelectModels.js
const SelectModels = ({ name, innerRef, types }) => (
<select name={name} required ref={innerRef}>
{types.map((type, index) => (
<option key={index}>{type}</option>
))}
</select>
);
export default SelectModels;
// usage
import SelectModels from './SelectModels.js'
<SelectModels name={`${fieldName}.modelType`} innerRef={register({ required: true })} types={allModelTypes}/>
The main idea is to identify the most re-usable components, so you will able to reuse them across the application.主要思想是确定最可重用的组件,以便您能够在整个应用程序中重用它们。
See Composition vs Inheritance , Thinking in React请参阅组合与 Inheritance ,反应中的思考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.