从自定义 TextInput 传递值

Pass value from custom TextInput

我有一个非常简单但样式化的 TextInput,声明为自己的组件。

看起来像这样:

import React from 'react';
import { Text, View, TextInput } from 'react-native';
import styled from 'styled-components'

const StyledInput = styled.TextInput`
    margin-bottom: 16px;
    width: 345px;
    padding-left: 8px;
`;

class Input extends React.Component {
    constructor(props) {
        super(props);
        this.state = { text: '' };
    }

    render() {
        return(
            <StyledInput
                style={{height: 40, borderColor: 'gray', borderWidth: 1}}
                // onChangeText={(text) => this.setState({text})}
                value={this.state.text}
                placeholder={this.props.placeholder}
                secureTextEntry={this.props.isPassword}
            />
        )
    }
}

export default Input

我的意图是将该组件包含在场景中,并在文本输入发生变化时触发 onChangeText 事件。我已经尝试了无数种方法...但都没有成功传递值。

<Input style={{height: 40, borderColor: 'gray', borderWidth: 1}}
    onChangeText={(code) => this.setState({code})}
    label='Aktiveringskods'
    placeholder='Aktiveringskod:'
/>

但是使用常规的 TextInput 确实可以完美地工作:

<TextInput style={{height: 40, borderColor: 'gray', borderWidth: 1}}
    onChangeText={(username) => this.setState({username})}
    label='Välj användarnamn'
    placeholder='Användarnamn:'
/>

我在这里错过了什么?

原因是您没有在自定义 Input 中将 onChangeText 传递给 TextInput

render() {
    return(
        <StyledInput
            {...this.props}
            style={{height: 40, borderColor: 'gray', borderWidth: 1}}
            value={this.state.text}
            placeholder={this.props.placeholder}
            secureTextEntry={this.props.isPassword}
        />
    )
}