【问题标题】:How to assign the value of a textfield to a hoistedState in compose?如何在撰写中将文本字段的值分配给提升状态?
【发布时间】:2021-11-22 09:25:37
【问题描述】:

我想制作一个可重用的组件,包括TextField,比如

@Composable
fun ReusableFormField(textFieldValue: TextFieldValue){
   --label stuff here--
   TextField(value = textFieldValue, onValueChange = {
            textFieldValue = it)
   })
   --helper stuff here
}

但我找不到将textFieldValue 分配给包装组件的方法,因为您无法通过参数中的refout 之类的引用传递变量。

【问题讨论】:

    标签: android kotlin textfield android-jetpack-compose


    【解决方案1】:

    您需要向ReusableFormField 提供一个 lambda 参数来更新值。

    @Composable
    fun ReusableFormField(
        value: TextFieldValue,
        onValueChange: (TextFieldValue) -> Unit
    ){
       // --label stuff here--
       TextField(value = value, onValueChange = onValueChange)
       // --helper stuff here
    }
    

    【讨论】:

      【解决方案2】:

      如果您记得上面的 textFieldValue 状态,您可以传递事件顶部并在那里修改状态。那么它将被重新组合。

      @Composable
      fun ParentComposable(){
          var textFieldValue by remember {
              mutableStateOf(TextFieldValue(""))
          }
          ReusableFormField(
              textFieldValue,
          ){
              textFieldValue = it
          }
      }
      
      @Composable
      fun ReusableFormField(
          textFieldValue: TextFieldValue,
          onValueChange: (TextFieldValue) -> Unit
      ){
          TextField(value = textFieldValue, onValueChange = onValueChange)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-07
        • 1970-01-01
        • 1970-01-01
        • 2018-02-23
        • 1970-01-01
        • 2019-12-31
        相关资源
        最近更新 更多