React Native TextInput auto grow when multilne

前端 未结 3 1118
后悔当初
后悔当初 2020-12-19 03:45

I want to create a TextInput which can grow automatically when it has multilines.

 

        
相关标签:
3条回答
  • 2020-12-19 04:04

    To implement auto grow multiline text input, you can adjust the height of the text input according to the content size in the textInput.

    you can use onContentSizeChange prop in TextInput and call a function to increase/decrease the height of input.

    Here is the quick example code

    export default class YourComponent extends Component {
    
      constructor (props) {
        super(props);
        this.state = {
          newValue: '',
          height: 40
        }
      }
    
      updateSize = (height) => {
        this.setState({
          height
        });
      }
    
      render () {
        const {newValue, height} = this.state;
    
        let newStyle = {
          height
        }
    
        return (
        <TextInput
          placeholder="Your Placeholder"
          onChangeText={(value) => this.setState({value})}
          style={[newStyle]}
          editable
          multiline
          value={value}
          onContentSizeChange={(e) => this.updateSize(e.nativeEvent.contentSize.height)}
        />
        )
      }
    
    }  
    

    OR

    You might want to use react-native-auto-grow-textinput

    0 讨论(0)
  • 2020-12-19 04:04

    With React Hooks

    Just to add to Shivam's answer, here is the version with hooks:

    import React, { useState } from 'react'
    
    export default function MyTextInput(props) {
        const [height, setHeight] = useState(42)
        return <TextInput
            style={styles.input, {height: height}}
            onContentSizeChange={e => setHeight(e.nativeEvent.contentSize.height)} />
    }
    
    0 讨论(0)
  • 2020-12-19 04:24

    Think that the React Native team fixed it in current version (0.59) with the multiline prop.

    This works for me

      <TextInput
        style={{
          width: '90%',
          borderColor: 'gray',
          borderWidth: 1,
          padding: 2,
        }}
        multiline
        onChangeText={text => this.setState({ text })}
        value={this.state.text}
      />
    
    0 讨论(0)
提交回复
热议问题