reactjs - 关注动态生成的自定义输入
问题描述
我正在实现一个自定义 SMS 代码验证,它将显示未定义数量的输入:
我想管理这些输入的焦点,但我不知道如何。
实际上,我有这样的自定义文本输入:
export function ConfirmationCodeInput(props) {
return (
<TextInput
style={styles.confirmationCodeInput}
keyboardType={"number-pad"}
maxLength={1}
ref={props.innerRef}
secureTextEntry={true}
selectionColor={'transparent'}
returnKeyType={"next"}
onChangeText={(event) => props.onTextChange(event)}
/>
)
还有我的父组件:
export function ConfirmationCode(props) {
let refs = [];
const [codeValue, setCodeValue] = useState(null);
function focusNextField(key) {
//What to do here ?
}
function createInputs(): Array<any> {
let inputs = [];
for (let i = 0; i < props.codeLength; i++) {
const ref = React.createRef();
refs[i] = ref;
const input = <ConfirmationCodeInput key={i}
innerRef = {ref}
onTextChange ={focusNextField}
/>;
inputs.push(input);
}
return inputs;
}
return (
<View style={{flexDirection: 'row', justifyContent: 'space-around'}}>
{createInputs()}
</View>
)
如何管理?
解决方案
更好的方法是定义一个您关注的隐藏输入,然后使用该输入的值显示在您的其他输入中。
export function ConfirmationCode(props) {
const [codeValue, setCodeValue] = useState(null);
function createInputs(): Array<any> {
let inputs = [];
for (let i = 0; i < props.codeLength; i++) {
const input = <ConfirmationCodeInput key={i}
value={codeValue[i] ? codeValue[i] : ''}
/>;
inputs.push(input);
}
return inputs;
}
return (
<View style={{flexDirection: 'row', justifyContent: 'space-around'}}>
<TextInput
keyboardType="numeric"
style={{ width: 1, height: 1, opacity: 0 }}
maxLength={6}
caretHidden={true}
autoFocus
onChangeText={text => setCodeValue(text)}
/>
{createInputs()}
</View>
)
像这样的东西。
推荐阅读
- python - 如何使用 Apache Spark/Python 将列表对象上传到 databricks DBFS
- javascript - React Native: Console Error Can't find variable: task (Image upload and store with Firebase)
- virtual-memory - TLB 和页表的参考位同步
- swift - 在 Swift、LinearGradient 和 Form - 背景重叠
- c++ - Embree: stream mode - how does gather and scatter work and what are pid and tid?
- node.js - Apollo 上传文件,createReadStream 不是函数
- .net-core - 无法从 Graph API 调用中获取组的显示名称 (sAMAccountName)
- flutter - Flutter NullSafety 在显示和更改 modalProgressHUD 后无法推送页面
- html - 我的文本框类似乎没有响应我的 CSS
- sql - 如何优化 postgres 中的交叉日期范围查询