gpt4 book ai didi

javascript - 如何从输入组件中获取值(学习目的)?

转载 作者:行者123 更新时间:2023-12-04 17:07:29 25 4
gpt4 key购买 nike

我的问题是我试图通过 API 调用处理我的输入值,用户定义了他想要的输入。
这是我得到值的地方:

 const handleClick = buttonTitle => async () => {
await renderField(buttonTitle).then(response => {
navigation.navigate('FormScreen', {
collectionKey: buttonTitle.slice(7),
paramKey: JSON.stringify(response),
});
});
};
渲染字段是一个 API 调用,它返回我 {"message": [{"_id": "618e4c23db08f70b719f3655", "author": "adicionarei posteriormente", "ceatedAt": "2021-11-12 08:12:32", "field": "abc", "fieldtype": "Text"}, {"_id": "618e4c9ddb08f70b719fae37", "author": "adicionarei posteriormente", "ceatedAt": "2021-11-12 08:14:35", "field": "Animal", "fieldtype": "Text"}]}然后我有我的表单组件,在那里我得到了一些需要的组件并为用户显示:
const FormScreen = ({route, navigation}) => {
return (
<Container>
<InputBody route={route.params.paramKey} navigation={navigation} />
</Container>
// => handle submit Input it in here ?
);
};
对于我的 inputbody组件我有以下代码(请记住( body.map 是 api 调用响应):
  return (
<>
{Object.keys(Body).length > 0 ? (
Body.map(item => (
<React.Fragment key={uuid.v4()}><Texto>{item.field}</Texto>
{renderContent(item.fieldtype,item.field)}
</React.Fragment>
))
) : (
<ActivityIndicator size="large" color="#eb6b09" />
)}
</>
)
}
然后我有我的 renderContent(我得到的字段类型为 string 和字段名称为 string)。
function renderContent(type,field) {
switch(type) {
case 'Numeric':
return <NumberInput key={field} keyboardType="numeric" />
case 'Text':
return <TextInput key={field} />
}
}
请记住:每种字段类型都可以出现多次。
(例如:我可以有一个表单具有超过 1 个文本输入),那么我的问题是:我如何处理我的输入值,知道它可以有任何类型的输入( Numeric or Text)?
obs:我可以显示任何类型的信息。

最佳答案


const Input = ({value,keyboardType,onChange})=>{
return(
<TextInput value={value} keyboardType={keyboardType} onChangeText={onChange} />
)
}


const [payload,setPayload] = useState({});

const onValue=(e,field)=>{
let tempPayload = {...payload};
tempPayload[field] = e;
setPayload(tempPayload)
}


const renderComponent = (fieldObj)=>{
switch(fieldObj.type):
case "Text":
return <Input keyboardType="default" onChange={(e)=>onValue(e,fieldObj.field)} value={payload[fieldObj.field]||""}/>
case "Number":
return <Input keyboardType="numeric" onChange={(e)=>onValue(e,fieldObj.field)} value={payload[fieldObj.field]||""} />
case "Dropdown":
return <Dropdown options={fieldObj.options} /> //if you want to add dropdown, radio buttons etc in future
}

这个想法很简单。将表单字段中的值存储在对象 payload 中.名称是字段的名称,例如。动物。该值是该字段的值。您还可以使用从 api 获得的所有键及其值初始化为空或默认值的对象。因此,如果我们渲染的字段是 Animal 和 Car。有效载荷将是
{
'Animal':'Tiger',
'Car':'BMW'
}
这是使用 onValue 函数处理的。您还可以在此函数中添加验证。例如,如果您使用 api 为该字段传递正则表达式,则可以使用正则表达式验证值。

关于javascript - 如何从输入组件中获取值(学习目的)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70260754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com