【问题标题】:Pass value from custom TextInput从自定义 TextInput 传递值
【发布时间】:2018-11-19 15:22:27
【问题描述】:

我有一个非常简单但样式化的 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:'
/>

我在这里错过了什么?

【问题讨论】:

    标签: react-native react-native-component


    【解决方案1】:

    原因是您没有在自定义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}
            />
        )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多