有条件 return 数据

Conditionally return data

我有这个功能:

 getFace(/* string */ face_name, /* int */ w, /* int */ h, /* int */ z) {
    const am = this.props.assetsManager;
    return {
      backgroundSize: 'contain',
      position: 'absolute',
      width: `${w}px`,
      height: `${h}px`,
      zIndex: z
  };

如果 face_nameface2 我需要 return 一种额外的样式,即 backroundColor: red

如何向 return 语句添加条件?

您可以添加一个对象,并根据这样的条件添加到它:

getFace( /* string */ face_name, /* int */ w, /* int */ h, /* int */ z) {
  const am = this.props.assetsManager;
  let returnObj = {
    backgroundSize: 'contain',
    position: 'absolute',
    width: `${w}px`,
    height: `${h}px`,
    zIndex: z
  };

  if (face_name == 'face2')
    returnObj.backgroundColor = 'red';

  return returnObj;
}

可以使用函数添加条件class

class BookmarkArticle extends React.Component {
  getClassName(){
     let classname="";
     if (condition){
       return classname
     }else{
       return classname
     }
  }
  render(){
     return(
         <div className={this.getClassName}></div>
)}
}