將組件的渲染方法拆分為被視為反模式的函式嗎?
我的意思是,如果 JSX 變得太大,我們可以完美地將它拆分為更多組件......
但是,下面的例子呢:
/**
* Renders the text inputs of the form.
*
* @returns {React.ReactElement} The text inputs.
*/
const renderInputs = () => (
<View style={styles.inputsContainer}>
<UsernameInput
ref={usernameInputRef}
label={t(
"authentication.signUp.accountInformation.usernameInputLabel"
)}
returnKeyType="next"
onChange={handleOnTextInputChange}
onSubmitEditing={() => emailInputRef.current.focus()}
containerStyle={commonStyles.textInputContainer}
/>
<TextInput
ref={emailInputRef}
label={t("authentication.signUp.accountInformation.emailInputLabel")}
maxLength={MAX_EMAIL_LENGTH}
textContentType="emailAddress"
keyboardType="email-address"
returnKeyType="next"
icon={{
name: "email",
type: "material",
color: colors.scorpion,
}}
onChange={handleOnTextInputChange}
onSubmitEditing={() => passwordInputRef.current.focus()}
containerStyle={commonStyles.textInputContainer}
/>
<PasswordInput
ref={passwordInputRef}
label={t(
"authentication.signUp.accountInformation.passwordInputLabel"
)}
textContentType="newPassword"
returnKeyType="next"
onChange={handleOnTextInputChange}
onSubmitEditing={() => repeatPasswordInputRef.current.focus()}
containerStyle={commonStyles.textInputContainer}
/>
<PasswordInput
ref={repeatPasswordInputRef}
label={t(
"authentication.signUp.accountInformation.repeatPasswordInputLabel"
)}
textContentType="oneTimeCode"
returnKeyType="done"
blurOnSubmit
onChange={handleOnTextInputChange}
containerStyle={commonStyles.textInputContainer}
/>
</View>
);
/**
* Renders a button for continuing to the next screen.
*
* @returns {React.ReactElement} The *'continue'* button.
*/
const renderContinueButton = () => (
<Button
disabled={isContinueDisabled}
uppercase
mode="contained"
onPress={handleOnContinue}
style={styles.button}
labelStyle={globalStyles.buttonLabel}
>
{t("authentication.signUp.accountInformation.continueButton")}
</Button>
);
return (
<View style={globalStyles.flexHorizontallyCenteredContainer}>
{renderInputs()}
{renderContinueButton()}
</View>
);
}
我應該避免在這里拆分代碼嗎?正如你所看到的......我正在為最“原子”的部分使用自定義組件......以及兩個內部輔助方法來使用相應的布局調整來呈現它們。
模式還是反模式?
uj5u.com熱心網友回復:
不,將 UI 抽象為不同的 JSX 組件并不是一種反模式。恰恰相反。推薦。
但是,我會認為您這樣做的方式是反模式。您不應該通過將 JSX 函陣列件作為普通 JS 函式行內呼叫來呈現它。它有效,但沒有必要。
而不是寫
<View style={globalStyles.flexHorizontallyCenteredContainer}>
{renderInputs()}
{renderContinueButton()}
</View>
您可以直接創建 JSX 組件作為子組件,View如下所示。
<View style={globalStyles.flexHorizontallyCenteredContainer}>
<renderInputs />
<renderContinueButton />
</View>
因為它們都是 JSX 組件。在這種情況下,通常期望 JSX 組件以大寫字母開頭并且不使用動詞命名。因此,我建議將它們命名如下。
const Inputs = () => {
return (...)
}
const ContinueButton = () => {
return (...)
}
雖然可以在另一個組件中定義組件,然后在主組件的渲染函式中創建它,但通常建議創建新檔案。因此,InputsandContinueButton將被放置在一個新檔案中,例如Inputs.jsand ContinueButton.js。您可以像往常一樣匯出它們并匯入它們。這使得在不同的地方重用組件成為可能。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/451964.html
標籤:javascript 反应 反应式 设计模式
