javascript 通过Switch语句呈现组件时TextInput键击出现问题

bxpogfeg  于 9个月前  发布在  Java
关注(0)|答案(1)|浏览(70)

目前面临与使用Switch陈述式的动态元件转译相关的问题。阅读下面的代码会更容易,以便更好地理解。
getCurrentComponent函数有一个Switch语句,它根据“Page”状态呈现所需的Step。该问题与TextInput有关-每次按键后,它都会停止键入。
在不使用函数getCurrentComponent的情况下呈现组件Step1时,不会出现此问题。

export default function AddProductModal({isVisible, toggleModal, page, setPage})  {
    
        const [title, setTitle] = useState('') 
    
        const getCurrentComponent = () => {
               switch (page) {
               case 1:
                   return <Step1/>;
               case 2:
                   return <Step2/>;
               }
        ;}
    
    
        const Step1 = () => (
            <ScrollView>
                <View style={styles.InputContainer}>
                    <Text style={{ fontFamily: 'Gilroy-SemiBold', fontSize: 18, marginTop: 30 }}>Title</Text>
                    <TextInput allowFontScaling={false} value={title} onChangeText={(value) => setTitle(value)} style={styles.singleInput} />
                </View>
            </ScrollView>
    )
    
    
    
    return (
         <View>
             {getCurrentComponent()}
         </View>

         {/* Rendering as below works. Above does not */}
         {/* {Step1()} */}

    )
}

字符串

um6iljoc

um6iljoc1#

我也面临着同样的问题时,编码动态数字的textInput设计。似乎与React Native功能组件生命周期有关。
当您在textInput中输入并触发状态更改时,AddProductModal()中的功能组件getCurrentComponent()将重新呈现。因此,最简单的修复方法是将已定义的功能组件移出主导出函数。

const Step1 = ({title, setTitle}) => (
    //Move it outside
    <ScrollView>
      <View style={styles.InputContainer}>
        <Text style={{ fontFamily: 'Gilroy-SemiBold', fontSize: 18, marginTop: 30 }}>Title</Text>
        <TextInput allowFontScaling={false} value={title} onChangeText={(value) => setTitle(value)} style={styles.singleInput} />
      </View>
    </ScrollView>
)

export default function AddProductModal({isVisible, toggleModal, page, setPage})  {

    const [title, setTitle] = useState('') 

    const getCurrentComponent = () => {
           //pass the required data & function by prop
           switch (page) {
           case 1:
               return <Step1 title={title} setTitle={setTitle} />;
           case 2:
               return <Step2/>;
           }
    ;}

    return (
         <View>
             {getCurrentComponent()}
         </View>
    )
}

字符串

相关问题