codememo

반응 재료 UI 레이블이 텍스트와 겹침

tipmemo 2023. 3. 4. 14:57
반응형

반응 재료 UI 레이블이 텍스트와 겹침

React 어플리케이션에서 Material UI를 사용하고 있으며 엔티티 업데이트 페이지를 구현하려고 합니다.이 경우 엔티티의 기존 값을 사용자가 갱신할 수 있도록 설정해야 합니다.기존 값은 입력 필드의 defaultValue 속성을 사용하여 설정되었습니다.

<div className="input-field">
   <input type="text" name="name" ref="name" defaultValue={this.state.name} />
   <label htmlFor="name" >Name</label>
</div>

이 방법을 사용하면 원하는 기능이 제대로 작동합니다.그러나 모든 텍스트 필드의 레이블은 해당 값과 겹칩니다.아래 스크린샷을 참조하십시오.

여기에 이미지 설명 입력

각 필드를 클릭하면 라벨이 예상대로 위로 이동합니다.그러나 페이지 로드 시 라벨은 위로 이동하지 않습니다.입력 필드의 값 속성을 onChange() 이벤트 핸들러와 함께 사용하려고 했지만 동일한 문제가 발생했습니다.정말 감사합니다.

이 애플리케이션의 완전한 소스 코드는, https://github.com/imesh/react-examples/tree/master/meetups/meetups-web-client 를 참조해 주세요.

이 페이지는, 다음의 URL 에 있습니다.https://github.com/imesh/react-examples/blob/master/meetups/meetups-web-client/src/components/UpdateMeetup.js

Github 문제 : https://github.com/Dogfalo/materialize/issues/5995

이는 값의 정의되지 않은 상태로 인해 발생합니다.

이 회피책은 폴백으로 사용할 수 있습니다.

value= this.state.name || '';

예: Material-UI의 경우

<div className="input-field">
   <input type="text" name="name" ref="name" value={this.state.name || ''} />
   <label htmlFor="name">Name</label>
</div>

Input Label에 소품 있음shrink. TextField에서 다음과 같이 사용할 수 있습니다.

<TextField
  // ... rest
  InputLabelProps={{ shrink: true }}  
/>

텍스트 필드 값을 기준으로 축소 조건을 추가하여 수정했습니다.

이 코드를 텍스트 필드에 추가합니다.Updateed (2022 )

InputLabelProps={{ shrink: field.value }}  

예:

<Controller
name="formatted_phone_number"
control={control}
render={({ field }) => (
  <TextField
    {...field}
    className=""
    id="formatted_phone_number"
    label="Phone"
    type="text"
    variant="outlined"
    fullWidth
    InputLabelProps={{ shrink: field.value }}  
  />
)}
/>

null & & defined가 아니면 값을 할당하는 조건으로 해결했습니다.여기 Formik 사용

<TextField
                    type="text"
                    label="Ending Month"
                    variant="outlined"
                    fullWidth
                    size="small"
                    name="endingMonth"
                    value={
                      values.endingMonth === null ||
                      values.endingMonth === undefined
                        ? ""
                        : values.endingMonth
                    }
                    helperText={touched.endingMonth && errors.endingMonth}
                    error={Boolean(touched.endingMonth && errors.endingMonth)}
                  />

같은 문제가 있었습니다만, 일관성이 없었습니다.즉, 라벨이 올바르게 표시되어 있을 때도 있고 겹칠 때도 있습니다.

다음을 시도해보니 잘 작동했습니다.기본적으로 데이터 없이 폼이 먼저 비워지고 다음으로 useEffect가 데이터를 가져와 데이터를 채우는 것입니다.isLoading 상태 변수를 설정했습니다. API에서 데이터를 가져온 후 처음에는 true로 설정되고 false로 설정됩니다.

isLoading이 false인 경우에만 모든 데이터를 표시합니다.이 방법은 올바르게 작동합니다.

코드 조각

export default function UserProfile(props) {
const classes = useStyles();
const [user, setUser] = React.useState({});
const [isLoading, setIsLoading] = React.useState(true);

const getUser = async () => {
    const requestOptions = {
        method: 'GET',
        cache: 'no-cache',
        headers: { 
            'Content-Type': 'application/json',
        },
        redirect: 'follow',
        referrerPolicy: 'no-referrer',            
    };

    const response = await axios.request(
        "/api/userprofile",
        requestOptions
    );

    const responseData = await response.data;
    
    setUser( responseData.userProfile );
    setIsLoading(false);
}

React.useEffect(() =>{
    getUser();
    console.log(user);
})

return(
    <div style={{padding:"10px"}}>
        <Grid container className={classes.card}>
            <Container component="main" maxWidth="xs">
            <>{ isLoading ? <div> </div> : 
            <div className={classes.paper}>
                <Typography variant="h6">User Profile</Typography>
                <TextField
                    key="Name"
                    variant="outlined"
                    margin="normal"
                    fullWidth
                    id="Name"
                    label="Name"
                    value={user.name}
                    InputProps={{
                        readOnly: true,
                    }}
                />
                <TextField
                    variant="outlined"
                    margin="normal"
                    fullWidth
                    id="email"
                    label="Email Address"
                    value={user.email}
                    InputProps={{
                        readOnly: true,
                    }}
                />
                <TextField
                    variant="outlined"
                    margin="normal"
                    fullWidth
                    id="phone"
                    label="Phone"
                    value={user.phone_number}
                    InputProps={{
                        readOnly: true,
                    }}
                />
            </div>
            }</>
            </Container>
        </Grid>
    </div>
);

}

이남아 . 2022년경에 래퍼 요소를 했습니다. 이치노TextFieldgrid로로 합니다.div그 문제를 해결해 주셨어요.

**Solution 1:** Set Shrink Attribute Based on Field Value if you want to move the label to outline only when it has value

  <TextField
   **key="title"**
   required
   id="title"
   label="Story Title"
   name="title"
   fullWidth
   value={this.state.title}
   InputLabelProps={{
   shrink: this.state.title?true:false,
   }}
/>

Solution 2: Set Shrink attribute as true If you are fine to display the label always at the outline of TextBox 

<TextField
          id="outlined-number"
          label="Number"
          type="number"
          **InputLabelProps={{
            shrink: true,
          }}**
        />


   

나한테 맞는 건 뭐든 시도해 볼 수 있어.

기능 기반 컴포넌트용입니다.

 const Example = () =>{
   const [name, setName] = useState("");
    const editName = (name) =>{
    setName(name);
  }

        return(
          <TextField
            required
            variant="outlined"
            margin="normal"
            fullWidth
            value={name}
            onChange={e => setName(e.target.value)}
            label="Enter Name"
          />
      )
  }

아래 작업:

<InputLabel shrink={true}>Select A Role</InputLabel>

InputLabelProps반응에서 기능 구성요소에 오류가 발생했습니다.

InputLabelProps=sshrink: true}}를 사용하여 상태 및 onSelect를 추가하여 축소 상태를 전환할 수 있습니다.

const [shrink1, setShrink1] = useState(false)

<TextField
            fullWidth
            id='filled-basic'
            label='Name'
            variant='filled'
            value={formState.name}
            onChange={(event) => setFormState({ name: event.target.value })}
            onSelect={() => setShrink1(true)}
            InputLabelProps={{ shrink: shrink1 }}
          />

언급URL : https://stackoverflow.com/questions/50955603/react-material-ui-label-overlaps-with-text

반응형