【问题标题】:React Native unit for text input value用于文本输入值的 React Native 单元
【发布时间】:2018-08-04 22:51:23
【问题描述】:

我想将单位添加到 textInput 值:

我尝试使用value = { this.state.totalWeight + " Kgs"},但没有结果!

我也尝试在onSubmitEditing = { () => { this.refs.firstInput.refs.value = this.state.totalWeight + " Kgs" } 中添加" Kgs",但同样没有结果!

有什么想法吗?

提前致谢!

【问题讨论】:

    标签: javascript reactjs react-native ecmascript-6


    【解决方案1】:
    state = {
       value: "",
       unit: "Kgs"
    }
    render(){
       return(
         <View style={{flexDirection: 'row', alignItems: 'center'}} >
                <TextInput value={this.state.value} onChangeText={(value) => this.setState({value})} />
                <View style={{marginRight: 10}} >
                    <Text>{this.state.value === '' ? '' : this.state.unit}</Text>
                </View>
         </View>       
       );
    }
    

    【讨论】:

    • 所以每次我输入一个数字,我都会得到一个“Kgs”! - 例如我输入“23”,值为:“2 Kgs 3 Kgs”
    • 哦对了!让我更新答案。这个解决方案对你来说可能有点老套。
    • 更新后的答案可能不是您真正想要的。但在我看来,它满足了需求。
    • 我知道了,谢谢!看看别人有没有更好的办法! :)
    【解决方案2】:

    所以我用这种方式!

    我的state

    this.state = {
      commodity: "",
      isFilled: false
    };
    

    然后我们有:

    <TextInput
      style={{ flex: 1 }}
      onChangeText={commodity =>
        this.setState({
          commodity,
          isFilled: false
        })
      }
      value={
        this.state.isFilled ? this.state.commodity + " Unit" : this.state.commodity
      }
      onFocus={() => this.setState({ isFilled: false })}
      onEndEditing={() => {
        if (this.state.commodity == "") {
          this.setState({ isFilled: false });
        } else {
          this.setState({ isFilled: true });
        }
      }}
      placeholder="Commodity"
    />;
    

    现在用户每次输入文本,编辑后都会添加UNIT。

    【讨论】:

    • 你的意思是用户可以改变文字颜色?
    • Unit 文本是 TextInput 值的一部分,因此用户可以选择并删除它。
    • 对不起,我误解了这个问题:D - 你可以使用 2 &lt;Text&gt; 然后
    猜你喜欢
    • 2018-04-16
    • 2016-12-01
    • 2019-06-03
    • 2018-06-02
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多