根据内容大小设置多行textInput的初始大小

时间:2016-11-30 19:26:53

标签: javascript react-native ecmascript-6

我的组件中有一个多行textInput,我根据状态设置初始值。

我已经设置了一个onChange事件处理程序,可以根据包装文本的高度正确调整字段的高度。但是,只有当我手动输入字段时才会调用它。

所以我想弄清楚如何从textField获取计算出的内容高度及其初始文本。

class MyComponent extends Component {

    _textInput:any;

    constructor(props) {
        this.handleTextInputChange= this.handleTextInputChange.bind(this)
        this.handleLayout= this.handleLayout.bind(this)
        this.state.text = "The quick brown fox jumped over the lazy dog"
    }

    handleTextInputChange(evt){
        // This works, but only fires on manual input
        const height = Math.max(35, evt.nativeEvent.contentSize.height) 
        this.setState( {text: evt.nativeEvent.text, contentHeight:height})
    }

    handleLayout(evt){
        // I can't seem to get anything useful from this event
    }

    componentDidMount(){
        for (key in this._textInput) console.log(key)
        //  I can't get anything useful from the 
        // _textInput object itself either
    }

    render() {

        return(
            <TextInput
            ref={textInput => (this._textInput = textInput)}
            multiline={true}
            onChange={this.handleTextInputChange}
            onLayout={this.handleLayout}
            style={{height: this.state.contentHeight}}
            value={this.state.text}
            />
            )   
    }
}

注意:onContentSizeChange未被使用,因为它似乎在RN 0.38中被打破

1 个答案:

答案 0 :(得分:0)

通过制作具有相同样式属性的常规Text元素并使用其onLayout回调来设置TextInput的高度来解决此问题。它需要一些填充调整才能正确排列。

以下是相关部分:

handleTextLayout(evt){
    this.setState({contentHeight:evt.nativeEvent.layout.height+12})
}

handleTextInputChange(evt){
 this.setState( {text: evt.nativeEvent.text})
}

renderTextInput(){
    return(
        <View style={{flex:1, flexDirection:"row", flexGrow:1}}>

        <Text   
        onLayout={this.handleTextLayout}
        style={
            [styles.textInput, {color: "blue", paddingLeft:4, paddingRight:4}] }>
            {this.state.text}
            </Text>

            <TextInput
            multiline={true}
            onChange={this.handleTextInputChange}
            style={[styles.textInput, {position:"absolute", top:0, left:0, right:0,height: this.state.contentHeight} ]}
            value={this.state.text}
            />
            </View>
            )
}

解决方案的灵感来自this github issue